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
});
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With