TonyO
TonyO

Reputation: 209

JavaScript to detect what checkboxes and checked and perform action

I have a jsp page with a checkbox declared like so

<form:checkbox path="affProgramSessionList[${status.index}].programSessionDetailId" id="checkbox_${session.id}" data-id="${session.id}" value="${session.id}" />

it is contained within a for loop and basically a checkbox is displayed for each session. That all works fine and I have no issues.

currently when a check box is checked this function is ran

$("input[id*='checkbox_']").each(function () {
    $(this).click(function(){
        var dataid = $(this).attr("data-id");
        var divId = "fullAttendence_" + dataid;
        var divIdAttendee = "attendeeType_" + dataid;

        $('#' + divId).toggle(this.checked);
        $('#' + divIdAttendee).toggle(this.checked);
    });

});

This then results in some other checkboxes being checked and some divs that were hidden being shown.

I am now adding in functionality for if someone had checked some check boxes and saved and comes back to the page then those check boxes will be checked.

I have that part working but I can't get the function to run properly.

I have the following

if ($("input[id*='checkbox_']").is(':checked')) {

    var dataid = $(this).attr("data-id");
    var divId = "fullAttendence_" + dataid;
    var divIdAttendee = "attendeeType_" + dataid;

    $('#' + divId).toggle(this.checked);
    $('#' + divIdAttendee).toggle(this.checked);
}

This function DOES get called as I tested it with a console.log.

the issue is that

var dataid = $(this).attr("data-id");

comes back as

undefined

Now my assumption right now is just that my new function to check for checked boxes and the other function that gets call are not working quite the same and my function doesn't know which check box was checked just that at least one was?

any help is really appreciated.

Upvotes: 1

Views: 66

Answers (1)

Oliver Baumann
Oliver Baumann

Reputation: 2289

if ($("input[id*='checkbox_']").is(':checked')) {

... will filter out the first checked input and operate on that. If you want to iterate on all checkboxes, use this construct:

$("input[id*='checkbox_']").each(function() {
    if ($(this).is(':checked')) {
        // do something
    }
});

Upvotes: 1

Related Questions