Try using .add()
$(selector_1).add(selector_2).trigger('change');
문제
I'm trying to trigger a "change" event on two different selectors using jQuery, but for some reason, when I do this, only the first selector actually seems to trigger the event.
This is what I'm doing:
jQuery(first_field).trigger('change');
jQuery(second_field).trigger('change');
I want to do this because I have functions for the change events on selector_1
and selector_2
that disables certain input fields in a form. The way that I'm assessing that the second change event isn't being triggered is by the fact that those input fields are not being disabled.
I know the disabling functions work and the jQuery .change events work because if I simply change the form using my mouse, the functions behave as I expect.
Update:
Here is the enable/disable code:
function disable_field(s) {
if ($(s).disabled != true) {
$(s).disabled = true;
/* Reset text value */
if ($(s).type == "text") {
$(s).value = "";
/* Reset selected value */
} else if ($(s).type == "select-one") {
$(s).selectedIndex = 0;
}
}
}
function enable_field(s) {
if ($(s).disabled != false) {
$(s).disabled = false;
}
}
Note that this code is being used with Qualtrics; survey software that allows you to put JS along with your questions. They have their own selector assigned to $()
which only allows ids.
Here is the .change
code:
jQuery(first_field).change(function() {
/* Parse id */
var the_id = this.id;
var this_question = the_id.slice(-1);
the_id = the_id.substring(0, the_id.length - 3);
/* Create selectors */
var selector2 = the_id + '2~' + this_question;
var selector3 = the_id + '3~' + this_question + '~1~TEXT';
/* Handle toggle */
if (this.selectedIndex == 1) {
disable_field(selector2);
disable_field(selector3);
} else {
/* Account for value of second_field */
if ($(selector2).selectedIndex != 1;) {
enable_field(selector3);
}
enable_field(selector2);
}
});
jQuery(second_field).change(function () {
/* Parse id */
var the_id = this.id;
var this_question = the_id.slice(-1);
the_id = the_id.substring(0, the_id.length - 3);
/* Create selectors */
var selector3 = the_id + '3~' + this_question + '~1~TEXT';
/* Handle toggle */
if (this.selectedIndex == 1) {
disable_field(selector3);
} else {
enable_field(selector3);
}
});
해결책
Try using .add()
$(selector_1).add(selector_2).trigger('change');