Change FORM SELECT (dropdown menu) depending on other dropdown in JS/Jquery
I have a form with two drop down menus and I want the selectable values in the second drop down menu to change depending on what is chosen with the first drop down
This is drop down one:
<select name="cat" id="1">
<option>MAMMAL</option>
<option>REPTILE</option>
<option>BIRD</option>
</select>
And depending on the selection I immediately want one of these forms displayed:
<select name="type" id="type1">
<option>CAT</option>
<option>DOG</option>
</select
<select name="type" id="type1">
<option>SNAKE</option>
<option>LIZARD</option>
</select
<select name="type" id="type1">
开发者_运维百科<option>HEN</option>
<option>ROBIN</option>
</select
The form is for multiple entries so there's many rows with the id number increasing each time. My jQuery so far is:
$(document).ready(function()
{
$(".cat").live("click", function(event)
{
cid=event.target.id;
catchosen = event.target.value;
switch (catchosen)
{
case 'MAMMAL':
case 'REPTILE':
case 'BIRD':
return {}
};
event.preventDefault();
});
});
How do I change/replace the values in a dropdown list with jQuery?
Firstly, if you use the selector $(".cat")
, you should have your first select box the class cat
assigned. But it's always good to select using a id
in this case. And I would suggest you to use change
event instead of click
event on detecting change of select option of the first select box.
You can use the .empty()
jquery function to clear the 2nd drop down's options and then use .append()
to add new options to it.
Something like
$("#type1").empty(); //clear all options
$("#type1").append('<option value="CAT">CAT</option>');
Give separate ids for you select. i.e, type1, type2 and type3. Change youe script like this.
$(document).ready(function()
{
$(".cat").live("click", function(event)
{
catchosen = this.value;
$("#type1, #type2, #type3").hide();
switch (catchosen)
{
case 'MAMMAL':
$("#type1").show();
break;
case 'REPTILE':
$("#type2").show();
break;
case 'BIRD':
$("#type3").show();
break;
};
});
});
精彩评论