Details of obtaining, assigning and registering the radio value in HTML

Time:2020-2-25

1. Radio group

As long as the name is the same, it is a group, that is, only one group can be selected, as follows:

Copy code

The code is as follows:

<span>group1:</span>
<input type=”radio” checked=”checked” name=”group1″ />radio1
<input type=”radio” name=”group1″ />radio2
<input type=”radio” name=”group1″ />radio3

<span>group2:</span>
<input type=”radio” checked=”checked” name=”group2″ />radio4
<input type=”radio” name=”group2″ />radio5
<input type=”radio” name=”group2″ />radio6

The effect is as follows:
 

2. Get the selected radio node

Using jQuery is very convenient. Select group first, and then filter the checked ones, as follows:

Copy code

The code is as follows:

var group1 = $(“[name=’group1′]”).filter(“:checked”);
console.log(group1.attr(“id”));

3. Select a radio node

Use jQuery to set the checked property:

Copy code

The code is as follows:

$(“#radio2”).attr(“checked”, “checked”);

4. Select a radio node

Remove checked property:

Copy code

The code is as follows:

$(“#radio1”).removeAttr(“checked”);

As a result, none of a set of radios may be selected.

5. Register and select to select events

Or use the on function of jQuery to register the change event, as follows:

Copy code

The code is as follows:

$(“[name=’group1′]”).on(“change”,
function (e) {
console.log($(e.target).val());
}
);

In this way, as long as any one of group1 is selected, the function will be triggered.