user2571510
user2571510

Reputation: 11377

How to assign variable number of checkbox values to variables in jQuery?

I have an HTML form with a number of checkboxes that all have the same class="shared". I use the following to limit the number of checkable checkboxes to 3 at a time which works as intended:

$(document).on('change', '.shared', function() {
    var countShared = $('.shared:checked').length;
    if(countShared > 3 && $(this).is(':checked')) {
        alert("You can only select up to 3 departments to share with.");
        $(this).prop('checked',false);
    }
});

Now my problem is the following:

I have 3 variables, shared1, shared2 and shared3 and want to assign the values from the checked checkboxes above to these variables. I am looking for something that assigns the value of the 1st checked checkbox to variable shared1, the value of the 2nd checked checkbox to shared2 and the value of the 3rd checked checkbox to shared3.

Usually I would try an .each loop for something like this and go by the class .shared but I don't know how to apply this here as there could also be less than 3 or no checkboxes checked and I don't know which ones are.

How can I realise this ?

Upvotes: 0

Views: 280

Answers (2)

Subha
Subha

Reputation: 1051

If you have all the check box elements inside a parent, you can try the following -

$(YourSelector).index()

This will return you the index number of the checkbox and you can assign to respective variables.

just check where index is 1 and assign to shared1 variable and so on.

Upvotes: 1

fstanis
fstanis

Reputation: 5534

Initially set each of the variables to false.

Then, if there are no boxes checked, you're done. If there's one, just set shared1 to true. If there's two, set shared1 and shared2 to true and finally, if there are three checked boxes, set all three to true.

shared1 = false;
shared2 = false;
shared3 = false;
var checkedBoxes = $('.shared:checked');
if (checkedBoxes[0]) shared1 = true;
if (checkedBoxes[1]) shared2 = true;
if (checkedBoxes[2]) shared3 = true;

Upvotes: 1

Related Questions