javascript - jQuery, if any "one" value changes - Stack Overflow

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

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

I want to prise 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
});

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

I want to prise 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
});
Share Improve this question asked Aug 11, 2011 at 21:40 iNkiNk 831 silver badge12 bronze badges 2
  • No way... I mean I 'didn't' try it, but... <_<, yeah let me try that. – iNk Commented Aug 11, 2011 at 21:43
  • Sorry, I mis-read it at first. It won't work the way you have it. – user113716 Commented Aug 11, 2011 at 21:44
Add a ment  | 

3 Answers 3

Reset to default 7

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 mon 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 ing 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.

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745099374a4611179.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信