Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, if any "one" value changes

I have a piece of code where this guy wrote thirty functions for when a group of form values change.

I want to comprise them into a single function

$('#jobs_held').change(function() {
// do something, with a little variation
});

$('#residence_years').change(function() {
// do something, with a little variation
});

$('#how_long').change(function() {
// do something, with a little variation
});

Is there anyway I could do something like...

$('#jobs_held', '#residence_years', '#how_long').change(function(){
// do something, with a little variation
});
like image 651
iNk Avatar asked May 25 '26 04:05

iNk


2 Answers

Join them into a single string to use the multiple-selector[docs].

$('#jobs_held,#residence_years,#how_long').change(function(){
    // do something, with a little variation

    // "this" can be used to refer to the specific element 
    //     that received the event.

    alert( this.id ); // to alert the ID of the element
});

...or find some common identity like a class to select them all.

like image 197
user113716 Avatar answered May 27 '26 16:05

user113716


Give them all a class, e.g. "question", then simply $('.question').change(function() {});

You can access the id of the changed element within the function, if you need to vary it based on type.

edit: I suggested the class method over the multi-select as it's easier to maintain (you can add elements to the HTML without coming back to edit the JS). But yeah it's true, a multi-select is more inline with the actual question. And also, the better solution if altering the HTML is not viable.

like image 23
numbers1311407 Avatar answered May 27 '26 16:05

numbers1311407



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!