HTML DOM Input Radio name 属性


HTML DOM Input radio name 属性用于设置或返回 input radio 字段的 name 属性。name 属性在将表单数据提交至服务器之后识别表单数据时具有帮助作用。JavaScript 还可以使用 name 属性来引用表单元素,以便稍后进行处理。

语法

以下是语法 −

设置 name 属性。

radioObject.name = name

在此,name 用于指定单选按钮名称。

示例

让我们看一个 radio name 属性的示例 −

实时演示

<!DOCTYPE html>
<html>
<body>
<h1>Input radio name Property</h1>
<form id="FORM1">
FRUIT:
<input type="radio" name="fruits" id="Orange">Orange
</form>
<p>Change the name of the above radio button by clicking the below button</p>
<button type=”button” onclick="changeName()">CHANGE NAME</button>
<p id="Sample"></p>
<script>
   function changeName() {
      document.getElementById("Orange").name ="colors" ;
      document.getElementById("Sample").innerHTML = "Radio button name is now colors";
   }
</script>
</body>
</html>

输出

这将产生以下输出 −

单击 CHANGE NAME 按钮时 −

在以上示例中 −

我们首先在 form 中创建一个 input 元素,其 type="radio",name="fruits",id="Orange" −

<form>
FRUIT:
<input type="radio" name="fruits" id="Orange">Orange
</form>

然后我们创建一个 CHANGE NAME 按钮,当用户单击时将执行 changeName() 方法 −

<button type=”button” onclick="changeName()">CHANGE NAME</button>

changeName() 方法使用 getElementById() 方法来获取输入字段类型为单选并且设置其名称属性值为“colors”。然后,此更改反映在 ID 为“Sample”的段落中,并使用其 innerHTML 属性显示预期的文本

function changeName() {
   document.getElementById("Orange").name ="colors" ;
   document.getElementById("Sample").innerHTML = "Radio button name is now colors";
}

更新日期:15-2-2021

84 浏览量

开启您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.