简体   繁体   中英

Why can't I check this radio button using jQuery?

Here are my radio buttons:

<input type="radio" name="coolSwitch" value="0">Off
<input type="radio" name="coolSwitch" value="1">On

When I load the page, the second button is already clicked. I want to run JS to check the first one. Here's my JS:

$('input[type="radio"][name="heatSwitch"]')[0].prop('checked',true);

But I get this error: $(...)[0].prop is not a function(…)

Why?

It's because you are accessing the DOM element with an index of 0 in the jQuery object . You can't use jQuery methods on native DOM elements, which is why you're seeing an error.

Use the .eq() method to get a jQuery object (rather than a DOM element) by its index:

$('input[type="radio"][name="heatSwitch"]').eq(0).prop('checked', true);

As a side note, it's worth mentioning that you don't even have to use the .prop() method. If you're accessing a DOM element, just modify the checked property directly:

$('input[type="radio"][name="heatSwitch"]')[0].checked = true;

or without jQuery:

document.querySelector('input[type="radio"][name="heatSwitch"]').checked = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM