简体   繁体   中英

jQuery: Single change event to fire multiple functions not working

I'm systematically building jQuery functions such that the css classes of various inputs in a web form have dependencies on other inputs (ie when a given input has a given value, the "hide" class is removed from the appropriate subsequent input etc.)

A specific (working) example of the jQuery I am using is:

$(document).ready(function(){               
    $("input[name$='q_4']").change(function(){
        if(this.value == 'Yes') {
             $('#qu_5').removeClass('hide');
        } else {
             $('#qu_5').addClass('hide');
        }
    });             
});

In this example, the dependent question div (#qu_5) depends on the value entered via radio button for (name=q_4) to be "Yes".

Because I am building these functions dynamically (users can edit properties of questions such that they have these kinds of display dependencies) via a database, I end up with multiple chunks of this code on a page with several interdependent inputs. Each chunk of code has the name of the master question, the id of the slave question and the value that the slave relies on to be revealed. This also works as intended.

Sometimes however, one input should reveal multiple other questions so I end up with code something like:

$(document).ready(function(){               
    $("input[name$='q_87']").change(function(){
        if(this.value == 'yes') {
             $('#qu_88').removeClass('hide');
        } else {
             $('#qu_88').addClass('hide');
        }
    });                 

    $("input[name$='q_87']").change(function(){
        if(this.value == 'yes') {
             $('#qu_89').removeClass('hide');
        } else {
             $('#qu_89').addClass('hide');
        }
    });                     
});

This does not work. (and indeed stops all the reveal / hide functions working on that page)

I presume it is because jQuery/javascript isn't happy with the same event input[name$='q_87']").change firing two different functions? This is the only thing I can think of.

Does anyone have any advice as to how I could achieve what I want in a way that works? Thanks! :)

If you need a var and an array you can write it like this

var questions = {
  "q_87":["qu_88","qu_89"],
  "q_96":["qu_95","qu_99"]
}


$.each(questions,function(q,arr) {
  $("input[name$='"+q+"']").change(function(){    
    $("'#"+arr.join(",#")+"'").toggleClass('hide',this.value == 'yes'); 
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM