-2

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>

asked Mar 2, 2024 at 22:54

2 Answers 2

2

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>

answered Mar 3, 2024 at 0:07
Sign up to request clarification or add additional context in comments.

Comments

1

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);
});
answered Mar 2, 2024 at 23:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.