如何在jQuery中以编程方式改变单选按钮的状态
在这篇文章中,我们将使用jQuery改变单选按钮的选定选项。为了选择单选按钮的值,我们可以将“checked”设置为所需的选项。为了设置该属性,我们可以使用jQuery中的prop()方法。
语法:
$(selector).prop("checked", true);
注意:选择器,是要选择的单选题元素。
例子:让我们创建一个单选按钮组来选择一个最喜欢的板球运动员。我们已经创建了一个单选选项。默认情况下,”Sachin “将被选中。当我们点击按钮时,”Dhoni “选项将被选中,正如程序中给出的那样。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
<fieldset>
<legend>Who is Your Favorite Cricketer?</legend>
<input type="radio"
name="favorite"
value="Dhoni" />Dhoni<br />
<input type="radio"
name="favorite"
value="Shewag" />Shewag<br />
<input type="radio"
name="favorite" checked
value="Sachin" />Sachin<br />
<br />
<button id="selectID">Select option</button>
</fieldset>
<script>
$("#selectID").on("click", function () {
selectRadio();
});
function selectRadio() {
let radioOption = jQuery("input:radio[value=Dhoni]");
// This will select the radio button
radioOption.prop("checked", true);
}
</script>
</body>
</html>
输出:
改变无线电状态