sonam
sonam

Reputation: 3760

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
        });

Upvotes: 5

Views: 15818

Answers (2)

bipen
bipen

Reputation: 36531

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
});

Upvotes: 11

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 6

Related Questions