I have a table like so:
<table>
<tr>
<td>
<input type="radio" name="Sample1" id="Sample1" value="1" />
<input type="radio" name="Sample1" id="Sample2" value="1" />
</td>
<td>
<input type="radio" name="Sample2" id="Sample1" value="1" />
<input type="radio" name="Sample2" id="Sample2" value="1" />
</td>
etc....
</tr>
</table>
I want to be able to select a specific radio button by name and id. E.G., select the radio button with the name Sample2 and id Sample1. I tried doing this:
$('[id="Sample1"][name="Sample2"]').checked = true;
But no luck... How should I be doing this?
How to select an element by name with jQuery? The JavaScript getElementsByName() method can be used to select the required element and this can be passed to a jQuery function to use it further as a jQuery object.
Just type the name of the element without "<" and ">" characters. For example type P, not <P> if the answer is the <P> element.
Differentiate the concepts of ID selector and class selector: The only difference between them is that “id” is unique in a page and it is applied to one HTML element while “class” selector can apply to multiple HTML elements.
Approach: Use jQuery [attribute^=value] Selector to select the element with ID starts with certain characters. Example 1: This example selects that element whose ID starts with 'GFG' and change their background color.
$('#Sample1[name="Sample2"]').attr('checked','checked');
but elements can only have one id so maybe you want class instead of id
$('.Sample1[name="Sample2"]').attr('checked','checked');
then your html
<table>
<tr>
<td>
<input type="radio" name="Sample1" class="Sample" value="1" />
<input type="radio" name="Sample1" class="Sample" value="1" />
</td>
<td>
<input type="radio" name="Sample2" class="Sample1" value="1" />
<input type="radio" name="Sample2" class="Sample2" value="1" />
</td>
</tr>
</table>
EDIT
made some changes here is a working demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With