2014-04-01 43 views
2

我正在使用jQuery來處理選擇窗體的所有複選框。這裏是我的代碼:使用jquery重新選擇所有複選框導致奇怪的行爲

$(function() { 
     $('#selectall').on('click', function() { 
      $('.selectedId').attr('checked', $(this).is(":checked"));  
     }); 
    }); 

    <input type="checkbox" id="selectall">Select all</input> 
    <input type="checkbox" name="industry1" id="industry1" value="1" class="selectedId"> 
    <input type="checkbox" name="industry2" id="industry2" value="1" class="selectedId"> 

當我檢查了selectall id checkbox,它選擇所有的複選框與類selectedId。當我再次點擊它時,它會刪除所有的檢查。

雖然我的問題是,在最初選擇所有/取消選擇所有它不再操作,因爲我不能選擇所有。

任何想法我應該做的在我的JavaScript將解決這個問題?

謝謝!

+1

你想一個奇怪的答案,去與你的怪異行爲? – adeneo

+0

可能重複[檢查取消選中所有複選框與另一個複選框使用jquery](http://stackoverflow.com/questions/15504643/check-uncheck-all-checkboxes-with-another-single-checkbox-use-jquery) – epascarello

回答

3

使用複選框屬性,而不是它們的屬性

$(function() { 
    $('#selectall').on('click', function() { 
     $('.selectedId').prop('checked', this.checked);  
    }); 
}); 

http://jsfiddle.net/VmnE2/