1

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.

2
  • 1
    try if ($(a).is(":checked")) { Commented Jun 29, 2015 at 3:40
  • make 'a' query object by doing $(a) Commented Jun 29, 2015 at 4:10

2 Answers 2

3

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('');
    }


})

Sign up to request clarification or add additional context in comments.

Comments

0

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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.