Reputation: 635
I have a form that there are many dropdown menus. User selects an option and related textboxes appear. I used .delegate()
to get each change on select
s. But when user changes let say 3rd one, all selects change at the same time,
$(function() {
$("#formbody").delegate("select", "change", function(){
var type = $(this).find("option:selected").val();
$("input").hide().filter("." + type).show();
$(":button").show();
});
});
All selects are dynamically added into divs, with incrementing ids.
<div id="div1">
<select id="new">
<option value="one">one</option>
<option value="two">two</option>
</select>
<input class="one" name="first_input"/>
<input class="two" name="second_input"/>
</div>
<div id="div2">
<select id="new">
<option value="one">one</option>
<option value="two">two</option>
</select>
<input class="one" name="first_input"/>
<input class="two" name="second_input"/>
</div>
But because I do not know JQuery as I should, I could not figure out a solution.
Upvotes: 0
Views: 143
Reputation: 434616
This:
$("input")
matches all <input>
elements on the page. That's why $("input").hide()
is hiding all of them. You want something more like this:
$(this).closest('div').find('input').hide()...
to only work with the <input>
s that are inside your current containing <div>
.
Also, your <select>
uses "one" and "two" for the values but your classes are "first" and "second". I think you want your <select>
s to look more like this:
<select id="new">
<option value="first">one</option>
<option value="second">two</option>
</select>
And you should do something about the duplicate id="new"
attributes.
You also have $(":button").show()
but there are no buttons in sight.
Demo of the above fixes: http://jsfiddle.net/ambiguous/9fsc5/
Upvotes: 1
Reputation: 50767
Your select menu's have the same ID. Change the value of the ID's to be unique for each menu and you will have your solution.
<select id="new">
<option value="one">one</option>
<option value="two">two</option>
</select>
.....
<div id="div2">
<select id="new">
<option value="one">one</option>
<option value="two">two</option>
</select>
Those select lists have the same ID. all Javascript associated with them will effect both. Change one of those ID values, or use classes, such as
$(".new").delegate(etc, function(){
var thisSelectListValue = $(this).val; //use the select list we interacted with
//your other code will go here
Should do what you want now.
Upvotes: 1