使用jquery标记下拉值

时间:2015-07-06 04:00:15

标签: javascript jquery

我的下拉菜单有点问题,我想在值不为0时验证它们,所以我使用了这段代码:

$('select[name=seguimento]').change(function(){
    $('option:selected',this).attr('selected', true);
});

问题在于,当我更改选项时,它会被选中,但是当我再次更改它时,它会将所有选项标记为已选中,而不是删除已选择的选项。

我到处搜索,但没有找到解决办法。

我该怎么做? 谢谢!

1 个答案:

答案 0 :(得分:2)

您必须从未选中的选项元素中删除所选属性,以便

$('select[name=seguimento]').change(function () {
    $('option[selected]:not(:selected)', this).removeAttr('selected');
    $('option:selected', this).attr('selected', true);
});

如果所有选项elemnet都是兄弟姐妹(即,optgroup未被使用)

$('select[name=seguimento]').change(function () {
    $('option:selected', this).attr('selected', true).siblings('[selected]').removeAttr('selected');
});