Reputation: 1079
I'm looking to bind a change event to an input element, but only if its next sibling is a select element, so that when the input value changes, if it matches any of the options in the select element, then that option will be selected. I know I can just bind the event to all the inputs and then check if each of them has a select sibling, but that is more computationally expensive, so I'd rather not do that. Any ideas?
This is what I am currently using:
$("input").each(function () {
var elmt = $(this);
if (!elmt.next("select")) {
return;
}
elmt.on("change", function () {
if (elmt.next("select").has("option[value='"+elmt.val()+"']")) {
elmt.next("select").val(elmt.val());
}
else {
elmt.next("select").val("");
}
});
});
Upvotes: 1
Views: 281
Reputation: 13892
You can maybe you jquery .prev
$('inputs + select').prev().on(...);
give it a try
Upvotes: 1