Select All Checkboxes By ID/Class

后端 未结 8 1882
孤城傲影
孤城傲影 2021-02-07 12:27

I\'m really bad at Javascript and I\'m struggling to get my head round it.

What I\'m trying to do is get something to select all checkboxes. However everything I have fo

相关标签:
8条回答
  • 2021-02-07 12:34

    What if you give all of the checkboxes the same name + a number(ie. chkbox1, chkbox2,etc...). Then in your javascript you would create a for loop to go through the number of checkboxes you have, and do getElementByID("chkbox" + num) (where num is your loop variable).

    0 讨论(0)
  • 2021-02-07 12:40

    Try this using jQuery:

    $(".className").prop("checked", true);
    $("#idName").prop("checked", true);
    
    0 讨论(0)
  • 2021-02-07 12:52
    var array = document.getElementsByTagName("input");
    
    
    for(var ii = 0; ii < array.length; ii++)
    {
    
       if(array[ii].type == "checkbox")
       {
          if(array[ii].className == YOUR_CLASS_NAME)
           {
            array[ii].checked = true;
    
           }
    
    
       }
    }
    

    by ID:

    var checkbox = document.getElementById(YOUR_ID);
    
    if(null != checkbox)
        checkbox.checked = true;
    
    0 讨论(0)
  • 2021-02-07 12:52

    I always had a tough time with javascript. You might want to investigate the jQuery javascript library. It's greatly enhanced my ability to solve problems using javascript, as well as create more clear and concise code to manipulate and access the DOM.

    With jQuery you should be able to easily select all the checkboxes you'd like by ID and then loop through them setting their value to be checked.

    0 讨论(0)
  • 2021-02-07 12:54

    Using JQuery, you can do this very easilly!

    $(".ClassName").attr("checked", "true");
    

    or a single ID

    $("#ID").attr("checked", "true");
    

    See: Check All Checkboxes with JQuery.

    0 讨论(0)
  • 2021-02-07 12:55

    Javascript

    By class:

    var clist=document.getElementsByClassName("MyClass");
    for (var i = 0; i < clist.length; ++i) { clist[i].checked = "checked"; }
    

    By ID:

    var clist=document.getElementById("MyID");
    for (var i = 0; i < clist.length; ++i) { clist[i].checked = "checked"; }
    

    See also: Loop Over querySelectorAll Matches.

    jQuery

    By class:

    $('.myclass:input:checkbox').each(function() { this.checked = true; });
    

    By ID:

    $('#myID:input:checkbox').each(function() { this.checked = true; });
    

    Related: How to reset all checkboxes using jQuery or pure JS?

    0 讨论(0)
提交回复
热议问题