3

I need to isolate a variable n that is appended to end of a series of input checkboxes. ID=SubDocRecChk0, ID=SubDocRecChk1, ID=SubDocRecChk2, etc. I want to return the n of the checkbox id that is clicked. But when I run this code it always returns n as 5, no matter which one I check.

  for (var n = 0; n < 5; n++) {

        $("#SubDocRecChk" + n).on("click", function () {

            if ($(this).prop('checked') == true) {

                alert(n + " is checked");
            }
            else {
                alert(n + " is unchecked");
            }

        });
    }
enter code here

Any help would be appreciated.

Other resources I've checked but haven't found my specific case. Thanks.

How to check whether a checkbox is checked in jQuery?

Check if checkbox is checked with jQuery

Community
  • 1
  • 1
jfbouz23
  • 126
  • 2
  • 6
  • There is no reason to loop with ids. Use a common class! – epascarello Mar 30 '15 at 17:56
  • 1
    To solve a similiar problem I Always am used to: $("input[id^='SubDocRecChk']").on("click", function () { var n = parseInt($(this).attr('id').substring('SubDocRecChk'.length)); if ($(this).prop('checked') == true) { alert(n + " is checked"); } else { alert(n + " is unchecked"); } }); – gaetanoM Mar 30 '15 at 18:30
  • thanks gaemaf. This is a concise, creative solution to the issue. – jfbouz23 Mar 30 '15 at 19:32

0 Answers0