2015-12-03 59 views
1

如何刪除其他選中複選框每點擊我的模式 這是我的HTMLjQuery的 - 如何刪除其他選擇選擇

<div class="form-group"> 
    <label for="sel1">Select role:</label> 
    <select class="form-control" id="role" name="role"> 
     <option value="admin">Admin</option> 
     <option value="user">User</option> 
    </select> 
</div> 

在我的javascript

$(document).on('click', '.changeRole', function(){ 
    var role = "admin" or "user"; //just change test, just nvm of this 
    $("#role option[value='"+role+"']").attr('selected', 'selected'); 
}); 

因爲當我執行兩個時間就會變成這樣2被選中並在顯示器上出錯

<div class="form-group"> 
    <label for="sel1">Select role:</label> 
    <select class="form-control" id="role" name="role"> 
     <option value="admin" selected="selected">Admin</option> 
     <option value="user" selected="selected">User</option> 
    </select> 
</div> 
+0

相關:http://stackoverflow.com/questions/13343566/set-select-option-selected-by-value – Stryner

回答

0

全部清除

$(document).on('click', '.changeRole', function(){ 
    var role = "admin" or "user"; 

    //clear all first 
    $("#role option").removeAttr("selected"); 

    $("#role option[value='"+role+"']").attr('selected', 'selected'); 
});