2

I am trying to set checkbox value for a filter component using query selector (without jquery). If the value for the element is string then query selection is success however if it is a numeric it fails.

<div>
  <span>Manufacturer</span>
   <label>
   <input type="checkbox" name="manufacturer" value="apple">Apple</label>
</div>

<div>
  <span>Screen Size</span>
   <label>
   <input type="checkbox" value="16" name="storage">16 GB</label>
</div>
<button>Select</button>


 document.querySelector('button').addEventListener('click', function() {
   document.querySelector('input[name=manufacturer][value=apple]').checked = true;
   document.querySelector('input[name=storage][value=16]').checked = true;
 })

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'input[name=storage][value=16]' is not a valid selector.

https://jsfiddle.net/byqwsdog/1/

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Binish Mookken
  • 150
  • 2
  • 16
  • Possible duplicate of https://stackoverflow.com/questions/20306204/using-queryselector-with-ids-that-are-numbers – Lalit Nov 28 '17 at 10:12

2 Answers2

3

You might use " for the value of your selector : [key="value"]

document.querySelector('button').addEventListener('click',function(){
  document.querySelector('input[name="manufacturer"][value="apple"]').checked = true;
  document.querySelector('input[name="storage"][value="16"]').checked = true;
})
dewDevil
  • 381
  • 1
  • 3
  • 12
Stéphane Ammar
  • 1,454
  • 10
  • 17
1

See the specification:

Attribute values must be CSS identifiers or strings.


In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

16 starts with a digit, so it (unlike manufacturer, apple and storage) cannot be an identifier.


Strings can either be written with double quotes or with single quotes.

16 is not written with either of those, so it isn't a string.


You need to quote the number.

document.querySelector('input[name=storage][value="16"]')
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335