Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding on change event to group of input fields in jquery

I have three input fields as below:

 <input type="text" name="address" id="address"/>
 <input type="text" name="city" id="city"/>
 <input type="text" name="country" id="country"/>

How can i add onChange event to all of these fields at once something like this:

$("select the elements with id address,city,country").bind("change", function() {
            //do something
        });
like image 386
sonam Avatar asked Jan 17 '13 08:01

sonam


2 Answers

use , in id selector as @Rory said

OR

add a class to all this and call change function

<input type="text" name="address" id="address" class="className"/>
<input type="text" name="city" id="city" class="className"/>
<input type="text" name="country" id="country" class="className"/>

$('.className').bind("change", function(){
  //your stuff
});

HOWEVER

since it is an input field.. i recommend you to use..keyup(), using change you have to click out of the text box to make it fire.

$('.className').keyup(function(){
  //your stuff
});
like image 70
bipen Avatar answered Nov 07 '22 05:11

bipen


You can use , as you would in CSS to combine selectors. Try this:

$("#address, #city, #country").bind("change", function() {
    //do something
});

Alternatively you can add a class to each element and select that.

like image 43
Rory McCrossan Avatar answered Nov 07 '22 04:11

Rory McCrossan