我有一个包含 5 个选项的复选框。只能选择其中的两个。我想要做的是将选中的值传递给下拉列表。由于可以选择两个复选框,我希望将它们的值传递给两个下拉列表。这是我目前所拥有的。
HTML
<input class="theme" type="checkbox" name="theme" value="adventure" id="adventure"/><label for="adventure">Adventure</label>
<input class="theme" type="checkbox" name="theme" value="attraction" id="attraction"/><label for="attraction">Attraction</label>
<input class="theme" type="checkbox" name="theme" value="culture" id="culture"/><label for="culture">Culture</label>
<input class="theme" type="checkbox" name="theme" value="leisure" id="leisure"/><label for="leisure">Leisure</label>
<input class="theme" type="checkbox" name="theme" value="nature" id="nature"/><label for="nature">Nature</label>
<select id="list2">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>
<select id="list1">
<option value="adventure">Adventure</option>
<option value="attraction">Attractions</option>
<option value="culture">Culture</option>
<option value="leisure">Leisure</option>
<option value="nature">Nature</option>
</select>
jQuery
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="adventure"){
$("#list1").val("adventure");
}
if($(this).attr("value")=="attraction"){
$("#list2").val("attraction");
}
if($(this).attr("value")=="culture"){
$(".cultureInterests").toggle();
}
if($(this).attr("value")=="leisure"){
$(".leisureInterests").toggle();
}
if($(this).attr("value")=="nature"){
$(".natureInterests").toggle();
}
});
如您所见,此方法有问题,因为选择复选框的顺序超出了我的控制范围,而且我无法确定将值传递到何处。非常感谢任何帮助。
示例
Here's a JSFiddle of what I am trying to achieve. Notice how the dropdown lists value change when you click on Adventure or Attractions. http://jsfiddle.net/ajitks/3hdbgw79/
非常感谢!
最佳答案
尝试这样的事情:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
if ($('input[type="checkbox"]:checked').length == 1) {
$('select#list1').val($(this).val());
} else {
$('select#list2').val($(this).val());
}
}else{
$('select#list1').val($('select#list2').val())
$('select#list2').val('')
}
});
如果您不想要 if else 条件,我们可以使用条件(三元)运算符。
关于javascript - 将多个复选框值传递给 jQuery 中的下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261168/