Rishabh Yadav
Rishabh Yadav

Reputation: 25

Selecting an element with different value but similar id

How can you select an element with value 2 using jQuery, if they all have same name and id?

 <input type="radio" id="store" name="store" value="1">
    <input type="radio" id="store" name="store" value="2">
     <input type="radio" id="store" name="store" value="3">

jQuery that didn't work:

$('#store:input[type="radio", value="2"]').html();

Upvotes: 0

Views: 43

Answers (3)

user8897421
user8897421

Reputation:

jQuery's selector engine can't handle it, but you can use then native querySelector instead, after you fix your selector.

const v = document.querySelector('input#store[type="radio"][value="2"]').outerHTML;

console.log(v);
 <input type="radio" id="store" name="store" value="1">
 <input type="radio" id="store" name="store" value="2">
 <input type="radio" id="store" name="store" value="3">

querySelector and querySelectorAll don't care about the HTML requirement of unique IDs. They fetch all matches on the page.

Also, .html() didn't make sense for an input, so I printed its .outerHTML instead.

Upvotes: 0

Artur
Artur

Reputation: 628

Read about multiple attribute selector.

This should work: $('#store:input[type="radio"][value="2"]').html();

Upvotes: 1

CarlosM
CarlosM

Reputation: 79

You can't—there should only be one instance of any given #id on the page.

Upvotes: 1

Related Questions