1

I have a dynamic checkbox. All the checkbox has dynamic ID as shown in code below. This checkbox is bind using "TABLE1".

<input type="checkbox" class="level-one" id="22" name="chkRoles" value="RecordOne">
<input type="checkbox" class="level-one" id="22" name="chkRoles" value="Recordtwo">
<input type="checkbox" class="level-one" id="19" name="chkRoles" value="Recordthree">
<input type="checkbox" class="level-one" id="30" name="chkRoles" value="RecordFour">
<input type="checkbox" class="level-one" id="35" name="chkRoles" value="RecordFive">
<input type="checkbox" class="level-one" id="25" name="chkRoles" value="RecordSix">

I am fetching the data from other TABLE, let's say TABLE2. Which contain value19,22,25.

var sectionLevelOne = "19,22,25";
var levelArrayOne = sectionLevelOne.split(",");
$.each(levelArrayOne, function (index, value){
       $("chkRoles_"+id).prop("checked",true);
});

I want to checked those CHECKBOX whose ID is "19,22,25".

1 Answer 1

1

Firstly note that you have multiple elements with the same id. This is invalid as id attributes have to be unique. If you cannot achieve that, use data-id to store custom data on the element.

That aside, your code is not building a valid id selector based on the HTML you've shown as chkRoles is the class, not the id. You can also simplify the logic. Try this:

"19,22,25".split(',').forEach(id => {
  $(`[data-id="${id}"]`).prop('checked', true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="level-one" data-id="22" name="chkRoles" value="RecordOne">
<input type="checkbox" class="level-one" data-id="22" name="chkRoles" value="Recordtwo">
<input type="checkbox" class="level-one" data-id="19" name="chkRoles" value="Recordthree">
<input type="checkbox" class="level-one" data-id="30" name="chkRoles" value="RecordFour">
<input type="checkbox" class="level-one" data-id="35" name="chkRoles" value="RecordFive">
<input type="checkbox" class="level-one" data-id="25" name="chkRoles" value="RecordSix">

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

2 Comments

yes sir you right related ID. I am fresher so making silly mistake. :)
No problem, glad to help

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.