Playing with selects and javascript
My code is:
<select name='main'>
<option>Animals</option>
<option>Food</option>
<o开发者_如何转开发ption>Cars</option>
</select>
<select name='other'>
<option>Rats</option>
<option>Cats</option>
<option>Oranges</option>
<option>Audi</option>
</select>
How can I filter my second <select>
, so it would only show items which I want eg. if I choose Animals, my select would be:
<select name='other'>
<option>Rats</option>
<option>Cats</option>
</select>
and if I choose "Food", my <select>
would look like:
<select name='other'>
<option>Oranges</option>
</select>
Well, I hope you get the idea. Thanks.
You'd need to create some kind of association between the selects, I'd recommend using the data-*
attribute:
<select id="main_select" name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>
<select id="other_select" name='other'>
<option data-category="Animals">Rats</option>
<option data-category="Animals">Cats</option>
<option data-category="Food">Oranges</option>
<option data-category="Cars">Audi</option>
</select>
Once that's in place for all of the <option>
elements, the JavaScript code would look something like this:
EDITED, this works:
$(function() {
var cloned = $('#other_select option').clone();
$('#main_select').change(function() {
var selectedCategory = $(':selected', this).text();
var filtered = $(cloned).filter("[data-category='" + selectedCategory + "']");
$("#other_select option").replaceWith(filtered);
});
$('#main_select').change(); //fire the event initially.
});
jsFiddle example
You could add a change
event handler to the main
select box that then branches on which option was selected and then dynamically adds options to the other
select. The following assumes a select with id main
and id other
:
HTML:
<select name="main" id="main">
<option value="1">Cars</option>
<option value="2">Food</option>
<option value="3">Animals</option>
</select>
<!-- Default the other select to 'cars' -->
<select name="other" id="other">
<option value="Audi">Audi</option>
</select>
JavaScript:
$("#main").bind("change", function() {
var categories = $("#other").get(0);
categories.options.length = 0;
switch (this.value) {
case "1":
categories.options[0] = new Option("Audi", "Audi");
break;
case "2":
categories.options[0] = new Option("Oranges", "Oranges");
break;
case "3":
categories.options[0] = new Option("Rats", "Rats");
categories.options[1] = new Option("Cats", "Cats");
break;
}
});
Check out an example here: http://jsfiddle.net/andrewwhitaker/nRGC9/
The naive solution would be:
$('select [name=main]').change(function(){
var other = $('select [name=other] option');
switch($(this).val()){
case 'Animals':
other.each(function () { if (!isAnimal($(this).val()))
$(this).hide();
else
$(this).show();
});
//where isAnimal is a function that accepts a string parameter and checks whether its an animal or not
break;
case 'food':
//continue in the same manner......
}});
精彩评论