Check if checkbox is checked with jQuery

后端 未结 23 3117
忘了有多久
忘了有多久 2020-11-21 23:12

How can I check if a checkbox in a checkbox array is checked using the id of the checkbox array?

I am using the following code, but it always returns the count of ch

23条回答
  •  梦毁少年i
    2020-11-21 23:47

    Actually, according to jsperf.com, The DOM operations are fastest, then $().prop() followed by $().is()!!

    Here are the syntaxes :

    var checkbox = $('#'+id);
    /* OR var checkbox = $("input[name=checkbox1]"); whichever is best */
    
    /* The DOM way - The fastest */
    if(checkbox[0].checked == true)
       alert('Checkbox is checked!!');
    
    /* Using jQuery .prop() - The second fastest */
    if(checkbox.prop('checked') == true)
       alert('Checkbox is checked!!');
    
    /* Using jQuery .is() - The slowest in the lot */
    if(checkbox.is(':checked') == true)
       alert('Checkbox is checked!!');
    

    I personally prefer .prop(). Unlike .is(), It can also be used to set the value.

提交回复
热议问题