单击下拉列表时取消选中并选中复选框 [英] uncheck and check checkboxes when clicking dropdown list
问题描述
我想在单击下拉列表时删除选中的复选框,然后选中下拉列表上的复选框.例如我有这段代码
I want to removed the checked checkboxes when clicking the dropdown and check a checkboxes on the dropdownlist. for example I have this code
<input id="item-1" type="checkbox">item1</input>
<input id="item-2" type="checkbox">item2</input>
<input id="item-3" type="checkbox">item3</input>
<select id="dropdown">
<option value="1,2">check the item 1 and 2</option>
<option value="1,3">check the item 1 and 3</option>
<option value="1,2,3">check the item 2 and 3</option>
</select>
这是我的jquery代码
Here is my jquery code
$('#dropdown').live("change", function() {
//remove all the chekced checkboxes
$('input:checkbox').removeAttr('checked');
//check chekboxes
var selected = $('#dropdown :selected').val();
dataitem = selected.split(',');
$.each(dataitem, function(key, item) {
$('#item-' + item).attr('checked', true);
});
});
这里发生的是,当我添加此代码时
What happened here is that when i add this code
$('input:checkbox').removeAttr('checked');
它将删除所有选中的复选框,但是当我在下拉列表中选择时不会添加.但是当我删除该代码时,它将选中一个复选框,但不会在先前选中的复选框上删除.
it will removed all the checked chekboxes but it will not add when I select on a dropdownlist. but when I removed that code it will check a checkboxes but it will not removed on the previous checked checkboxes.
推荐答案
对于我来说似乎工作正常,我只是注意到<option value="1,2,3">
与文本不一致,并将其更改为<option value="2,3">
.
Seems to work just fine to me, I just noticed that <option value="1,2,3">
was inconsistent with the text and changed it to <option value="2,3">
.
请参阅: http://codepen.io/AlienHoboken/pen/knCHh
这篇关于单击下拉列表时取消选中并选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!