HTML DOM Input Radio name Property


The HTML DOM Input radio name property is used for setting or returning the name attribute of an input radio field. The name attribute helps in identifying the form data after it has been submitted to the server. JavaScript can also use the name attribute to refer form elements to manipulate later on.

Syntax

Following is the syntax for −

Setting the name property.

radioObject.name = name

Here, name is for specifying the radio button name.

Example

Let us look at an example for the radio name property −

Live Demo

<!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>

Output

This will produce the following output −

On clicking the CHANGE NAME button −

In the above example −

We have first created an input element inside a form with type=”radio”, name=”fruits”, id=”Orange” −

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

We then created a CHANGE NAME button that will execute the changeName() method when clicked by the user −

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

The changeName() method uses the getElementById() method to get the input field with type radio and set its name attribute value to “colors”. This change is then reflected in a paragraph with id “Sample” and using its innerHTML property to display the intended text −

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

Updated on: 15-Feb-2021

64 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements