Annie Tsai
Annie Tsai

Reputation: 117

JQuery - Iterate a collection of value

I have a collection of data:

q: "5,1,3,4"

I need to get those values and so I can have checkbox preselected

$('input[data-value=5]').prop('checked', true);
$('input[data-value=1]').prop('checked', true);
$('input[data-value=3]').prop('checked', true);
$('input[data-value=4]').prop('checked', true);

I know using index like q[0] could work, but is there any way that no need to hardcode it? Because I don't know how many values will be in this collection.

Can anyone help me with this?? Thanks a lot!!

Upvotes: 2

Views: 68

Answers (2)

Obsidian Age
Obsidian Age

Reputation: 42304

You can use a simple .each() loop to achieve this with jQuery, or Array.prototype.foreach() in vanilla JavaScript.

If you actually have a string of numbers to start off with, you'll need to split them out into an array by running .split() on the comma.

This can be seen in the following example:

// If you have a string rather than an array
const q = "5,1,3,4";
const values = q.split(",");

// If you start with an array
//const values = [5, 1, 3, 4];

$(values).each(function(index, value) {
  $('input[data-value=' + value + ']').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" data-value="1">
<input type="checkbox" data-value="2">
<input type="checkbox" data-value="3">
<input type="checkbox" data-value="4">
<input type="checkbox" data-value="5">

Upvotes: 3

Hikarunomemory
Hikarunomemory

Reputation: 4305

Split q to an array with comma and loop through each value to select the input you want and change the prop

q.split(",").forEach(function(value){
    $('input[data-value='+ value +']').prop('checked', true);
})

Upvotes: 5

Related Questions