Vy Do
Vy Do

Reputation: 52516

Javascript loop get name of checked checkbox

I have HTML to display checkbox those checked via a loop:

<!DOCTYPE html>

<html>
    <head>
        <title></title>
        <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
    </head>

    <body>
        <form>
            <input type="checkbox" name="bla_bla1" id="checkbox_1" onchange="getName();"/>
            <input type="checkbox" name="bla_bla2" id="checkbox_2" onchange="getName();"/>
            <input type="checkbox" name="bla_bla3" id="checkbox_3" onchange="getName();"/>
        </form>     
        <span id="checkboxConfirm_1"></span>
        <span id="checkboxConfirm_2"></span>
        <span id="checkboxConfirm_3"></span>

        <script>            
            function getName(){
                for(i = 1; i<4; i++){
                var a = "#checkbox_".concat(i.toString()) ;
                var b = "#checkboxConfirm_".concat(i.toString());               

                if ((a).is(":checked")) {
                    $(b).text($(a).attr("name"));
                } else {
                    $(b).text('');
                }
            }
            }
        </script>   
    </body>
</html>

But Javascript not work. Please help me resolve the problem.

Upvotes: 1

Views: 10114

Answers (2)

Ajowi
Ajowi

Reputation: 505

If you are in a position to use jQuery, then you can anchor on the exact form-id and loop as shown below. You can then create an array on that loop of use it however you want:

let cbCheckedArray = [];
let currentVal = '';    //may always just be 'on'
let currentName = '';
$("#form-id input:checkbox:checked").each(function() {
    currentVal = $(this).val();
    currentName = $(this).attr("name");
    cbCheckedArray.push(currentName);
    alert('here: '+currentName);
});

Upvotes: 0

Keval Bhatt
Keval Bhatt

Reputation: 6322

Don't use onChange for every checkbox And no need to use for loop use regex selector of css and it will solve your problem.

see this example: http://jsfiddle.net/kevalbhatt18/gpdjoyxx/1/

$('input[type="checkbox"]').change(function () {
    var index = $(this).index();
    console.log(index)
    console.log($("span[id^=checkboxConfirm]").eq(index))
    if ($(this).is(':checked')) {
        $("span[id^=checkboxConfirm]").eq(index).html($(this).attr("name"));
    } else {
        $("span[id^=checkboxConfirm]").eq(index).html('');
    }


})

Upvotes: 3

Related Questions