I am attempting to pre-populate a form which has inputs with values I am not able to change. One of the fields is a series of checkboxes and some of the values contain double quotes to represnt inches. I have an array of values I want to change to checked but I'm not sure how to target those inputs with values containing double quotes.
let sizeArr = ['short', 'under 28"', 'over 28"'];
sizeArr.forEach(function(val) {
console.log(val);
$(':checkbox[value='+ val +']').prop('checked', 'true');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<label>
Short
<input type="checkbox" value="short" />
</label>
<label>
Under 28"
<input type="checkbox" value="under 28"">
</label>
<label>
Over 28"
<input type="checkbox" value="over 28"">
</label>
I also tried replacing the double quotes with "
directly in the array, but the selector still doesn't seem to work:
let sizeArr = ['short', 'under 28"', 'over 28"'];
sizeArr.forEach(function(val) {
console.log(val);
$(':checkbox[value='+ val +']').prop('checked', 'true');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<label>
Short
<input type="checkbox" value="short" />
</label>
<label>
Under 28"
<input type="checkbox" value="under 28"">
</label>
<label>
Over 28"
<input type="checkbox" value="over 28"">
</label>
Instead of directly concatenate the value into the selector string you can use the filter function to manually match the element's value against the desired value.
sizeArr.forEach(function(val) {
$(':checkbox').filter(function() {
return $(this).val() === val;
}).prop('checked', true);
});