Looping through checkboxes with javascript

前端 未结 3 1128
庸人自扰
庸人自扰 2021-01-24 17:17

I have a number of checkboxes which I am wanting to check if they are checked (1) or not checked (0). I want to place the results in an array so that I can send them to the serv

相关标签:
3条回答
  • 2021-01-24 17:47

    Try this efficient way bruvo :) http://jsfiddle.net/v4dxu/ with proper end tag in html: http://jsfiddle.net/L4p5r/

    Pretty good link: https://learn.jquery.com/javascript-101/arrays/

    Also in your html end your tag /> i.e.

    <input class="publish" id="chkBox4" type="checkbox" checked>

    rest should help :)

    Code

    var checkArray = new Array(); 
    $('input[type=checkbox]').each(function () {
        this.checked ? checkArray.push("1") : checkArray.push("0");
    });
    
    alert(checkArray);
    
    0 讨论(0)
  • 2021-01-24 18:00

    Take into account that the first element you write is checkArray[1], as i starts with 1, instead of checkArray[0].

    Replace checkArray[i] with checkArray[i-1] inside the for bucle

    0 讨论(0)
  • 2021-01-24 18:11

    As mentioned in the answers above the problem is with the index(i). But if you want to simplify the code further, How about the following code?

    var checkArray = [];
    
    $('input.publish').each(function () {
       checkArray.push($(this).is(':checked'));
    });
    
    alert(checkArray);
    
    0 讨论(0)
提交回复
热议问题