How to dynamically listen for changes in field

Issue

I have several similar fields in my form:

<select class="form-control" name="Ops[1][WorkCentre]">..</select>
<select class="form-control" name="Ops[2][WorkCentre]">..</select>
...
<select class="form-control" name="Ops[n][WorkCentre]">..</select>  

I don’t know how many such fields there will be, as the user adds the fields dynamically.

I need some way of executing a java script function when any of these inputs changes, and inside that function I need to be able to access the key of the input which has changed with regards to the ‘Ops’ array.

Im happy to use jquery. I was thinking something like

$('select[name=Ops[i][WorkCentre]').change(function(i){
    // A function using i
});

Or maybe a Javascript event listener?

Any help is appreciated.

Solution

You can use event delegation:

// Listen for 'change' event on every element that has class 'form-control'
$(document).on('change', 'select.form-control', function() {
   var name = $(this).attr('name');
   // You code here ...
});

UPDATE

In order to extract the number from name attribute, you can set the name as follows:

name="Ops_[1]_[WorkCentre]"

and then split by ‘_’:

var number = $(this).attr('name').split('_')[1];

UPADATE #2

A better solution would be to set the number in a separate attribute like this:

<select class="form-control" name="Ops[1][WorkCentre]" data-number="1">..</select>

and then retrieve it like this:

var number = $(this).attr('data-number');

Answered By – kapantzak

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published