SolemnWool SolemnWool - 4 years ago 57
Javascript Question

When I check one checkbox, I want another similar checkbox to be ticked

I would like to add a feature to my current project that enables the user to only have to check a checkbox with the same content once. In my case, I have a recipes page with checkboxes of ingredients for each recipe to use while shopping and I would like to have it so that when the user checks the checkbox "Coriander" in one recipe, it also checks any other Coriander checkbox in any other recipe.

At the moment I am working with ids and labels, but this only works for unique ids obviously.

<input type="checkbox" id="checkbox2"><label for="checkbox2"> Coriander</label> <br>


My current idea is to use the same snippet of code as for un/check all type buttons, but instead use a class of Coriander rather than id but not sure that would work or if it is the most elegant way.

Any other ideas appreciated!

Answer Source

Using the ingredient's name: You first find the label corresponding to the clicked checkbox by its for-attribute. With its text content you find all other labels with the given content. Then you iterate through all of those labels finding their corresponding checkboxes by their id-attributes and set them to checked.

$("body").on('click', "input:checkbox", function(ev, ui){
    var chkid = $(this).attr('id');
    var chklb = $("label[for='" + chkid + "']").text();
    $.each($("body").find("label:contains('" + chklb + "')"), function(i, v){
        $("#" + $(v).attr('for')).prop('checked', true);
    });
});

This way you can use the ingredient as given in the label.

An easier option would be just using ingredient-specific classes, shortening the code considerably. The drawback on this is more work when changing anything, because you have to keep the classes consistent.

This might look like that:

<input type="checkbox" id="checkbox2" class="coriander"><label for="checkbox2"> Coriander</label>
<input type="checkbox" id="checkbox3" class="coriander"><label for="checkbox3"> More coriander</label>

And the corresponding JQuery part:

$("body").on('click', "input:checkbox", function(ev, ui){
    $("." + $(this).attr('class')).prop('checked', true);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download