0

I have a group of checkboxes in a div. Here is one as an example:

<input id="customer426693" name="customers" type="checkbox" class="filled-in form-check-input customerCheckbox customerRequired" value="426693">

I have also in my javascript function an array of values to be selected. Is there an elegant way to select all checkboxes that have values that exist in the array using jquery?

Thanks.

2
  • 1
    Show us your code. Commented May 15, 2018 at 16:01
  • "That have values" you mean checked? Commented May 15, 2018 at 16:08

1 Answer 1

1

Is that what you want?

var selectedList = [3,4,6];

function MakeSelected() {

    $("#checkBoxContainer").find("input").each(function(index,item){
    
        if(selectedList.indexOf( $(item).data("customerid") )>=0)
          $(item).prop("checked",true);
          
    });
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>
I deleted class to make more readable.
</p>

<div id="checkBoxContainer">

   <input id="customer1" type="checkbox" value="1" data-customerid="1" />1 <br>
   <input id="customer2" type="checkbox" value="2" data-customerid="2" />2 <br>
   <input id="customer3" type="checkbox" value="3" data-customerid="3" />3 <br>
   <input id="customer4" type="checkbox" value="4" data-customerid="4" />4 <br>
   <input id="customer5" type="checkbox" value="5" data-customerid="5" />5 <br>
   <input id="customer6" type="checkbox" value="6" data-customerid="6" />6 <br>

</div>

<button type="button" onclick="MakeSelected()">try it!</button>

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

1 Comment

Thanks, that is nice.

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.