"/> ">

Home >Web Front-end >Front-end Q&A >How to get the value of radio with jquery

How to get the value of radio with jquery

WBOY
WBOYOriginal
2023-05-28 16:47:293444browse

jQuery is a very popular front-end JavaScript library. In daily page development, we often use form elements and event processing. Among them, getting the value of the radio button is a common requirement. The following will introduce how to use jQuery to obtain the value of the radio button.

First, we need to prepare a set of radio button boxes. Take the following code as an example:

<form>
  <input type="radio" name="gender" value="男"> 男
  <input type="radio" name="gender" value="女"> 女
</form>

The name and value of the radio button are very important. The name identifies a group of radio buttons, while the value represents a unique identifier for each radio button. Note that each radio button needs to have the same name.

Next, we can use jQuery selectors to get these radio buttons. As shown below:

var $radios = $('input[name="gender"]');

This selector uses the attribute selector to select all radio button boxes named gender.

Now we have successfully obtained a set of radio button boxes. However, we also need to know which radio button is selected. In order to achieve this function, we can use the prop() method in jQuery. The prop() method is used to get or set the attribute value of an element. It can get the checked attribute of the element to determine whether a radio button is selected. The code is as follows:

var selectedValue = $radios.filter(':checked').prop('value');

In this code, we use the filter() method to select the selected radio button. Then, use the prop() method to obtain the value of this radio button. The variable selectedValue represents the value of the selected radio button.

Finally, if we want to get the label text of the selected radio button instead of the value, we can use the next() method in jQuery to get the label text. The code is as follows:

var selectedLabelText = $radios.filter(':checked').next('label').text();

Description: Since the radio button usually controls some state changes, we can put the above code in the event handler to automatically execute when the user clicks the radio button.

The above code demonstrates how to use jQuery to get the value of the radio button. In actual page development, we may need to handle more complex form elements and events, and we need to comprehensively use various jQuery methods and techniques to complete the task.

The above is the detailed content of How to get the value of radio with jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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