Change/Get check state of CheckBox

前端 未结 11 924
别跟我提以往
别跟我提以往 2020-12-03 02:30

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I\'ve tried something like this but it won\'t work.

JavaScript fu

相关标签:
11条回答
  • 2020-12-03 02:53

    You need this:

    window.onload = function(){
        var elCheckBox=document.getElementById("cbxTodos");
        elCheckBox.onchange =function (){
            alert("como ves");
        }
    };
    
    0 讨论(0)
  • 2020-12-03 02:57

    I know this is late info, but in jQuery, using .checked is possible and easy! If your element is something like:

    <td>
        <input type="radio" name="bob" />
    </td>
    

    You can easily get/set checked state as such:

    $("td").each(function()
    {
        $(this).click(function()
        {
            var thisInput  = $(this).find("input[type=radio]");
            var checked = thisInput.is(":checked");
            thisInput[0].checked = (checked) ?  false : true;
        }
    });
    

    The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object! ENJOY!

    0 讨论(0)
  • 2020-12-03 02:57
    <input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
    
    0 讨论(0)
  • 2020-12-03 03:03

    Needs to be:

    if (document.forms[0].elements["checkAddress"].checked == true)
    

    Assuming you have one form, otherwise use the form name.

    As a side note, don't call the element and the function in the same name it can cause weird conflicts.

    0 讨论(0)
  • 2020-12-03 03:04

    Here is a quick implementation with samples:

    Checkbox to check all items:

    <input id="btnSelectAll" type="checkbox">
    

    Single item (for table row):

    <input class="single-item" name="item[]" type="checkbox">
    

    Js code for jQuery:

    $(document).on('click', '#btnSelectAll', function(state) {
        if ($('#btnSelectAll').is(':checked')) {
            $('.single-item').prop('checked', true);
            $('.batch-erase').addClass('d-block');
        } else {
            $('.single-item').prop('checked', false);
            $('.batch-erase').removeClass('d-block');
        }
    });
    

    Batch delete item:

    <div class="batch-erase d-none">
        <a href="/path/to/delete" class="btn btn-danger btn-sm">
            <i class="fe-trash"></i> Delete All
        </a>
    </div>
    
    0 讨论(0)
提交回复
热议问题