jQuery - Targeting a checkbox with a value containing double quotes

27 Views Asked by At

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&quot;">
</label>

<label>
  Over 28"
  <input type="checkbox" value="over 28&quot;">
</label>

I also tried replacing the double quotes with &quot; directly in the array, but the selector still doesn't seem to work:

let sizeArr = ['short', 'under 28&quot;', 'over 28&quot;'];
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&quot;">
</label>

<label>
  Over 28"
  <input type="checkbox" value="over 28&quot;">
</label>

2

There are 2 best solutions below

0
Shahar Shokrani On BEST ANSWER

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);
});
0
Alexander Nenashev On

Use CSS.escape():

let sizeArr = ['short', 'under 28"', 'over 28"'];
sizeArr.forEach(function(val) {
    console.log(val);
    $(':checkbox[value='+ CSS.escape(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&quot;">
</label>

<label>
  Over 28"
  <input type="checkbox" value="over 28&quot;">
</label>