Home > Web Front-end > Front-end Q&A > How to set radio button to selected in jquery (two methods)

How to set radio button to selected in jquery (two methods)

PHPz
Release: 2023-04-10 14:26:13
Original
4084 people have browsed it

In front-end development, the radio button is a very common form control. In some cases, we may need to set a radio button to a selected state when the page loads instead of waiting for the user to manually operate it. At this time, we can use jQuery to achieve this requirement.

The following are two commonly used and simple methods.

Method 1: Use the .prop() method

The .prop() method is used to obtain the attribute value of the first matching element. We can use the .prop() method to set the selected state of the radio button. The specific implementation is as follows:

//选中id为radio1的单选框
$("#radio1").prop("checked", true);
Copy after login

In the above code, we first select the id selector of the radio button, and then use the .prop() method to set its selected status to true. In this way, after the page is loaded, the radio button will automatically become selected.

Method 2: Use the .attr() method

The .attr() method is used to obtain the value of the specified attribute. The following is the implementation of using the .attr() method to set the selected state of the radio button:

//选中name为radio的值为value的单选框
$("input[name='radio'][value='1']").attr("checked", true);
Copy after login

In the above code, we first selected the name selector of the radio button and specified the value as '1'. Finally, use the .attr() method to set its selected status to true.

It should be noted that when using the .attr() method to set the selected state of the radio button, you can also use the prop() method instead. The effect of the two is the same.

In addition to the above two methods, you can also use the .val() method to set the value of the selected radio button. The specific implementation can be practiced by yourself and will not be repeated here.

In summary, in front-end development, it is very simple and convenient to use jQuery to set the selected state of a radio button. We just need to choose the appropriate method to meet our needs.

The above is the detailed content of How to set radio button to selected in jquery (two methods). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template