teutara
teutara

Reputation: 635

How to change on select individually, while there are many selects

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 selects. 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

Answers (2)

mu is too short
mu is too short

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

Ohgodwhy
Ohgodwhy

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

Related Questions