Loop through checkboxes and count each one checked or unchecked

前端 未结 5 1331
野性不改
野性不改 2020-11-30 22:40

I\'ve run into a bit of an issue. Here\'s a brief explanation.

I have 12 check boxes on a standard form. What I need to do is loop through each of them and learn whi

5条回答
  •  时光说笑
    2020-11-30 23:25

    To build a result string exactly in the format you show, you can use this:

    var sList = "";
    $('input[type=checkbox]').each(function () {
        sList += "(" + $(this).val() + "-" + (this.checked ? "checked" : "not checked") + ")";
    });
    console.log (sList);
    

    However, I would agree with @SLaks, I think you should re-consider the structure into which you will store this in your database.

    EDIT: Sorry, I mis-read the output format you were looking for. Here is an update:

    var sList = "";
    $('input[type=checkbox]').each(function () {
        var sThisVal = (this.checked ? "1" : "0");
        sList += (sList=="" ? sThisVal : "," + sThisVal);
    });
    console.log (sList);
    

提交回复
热议问题