HTML DOM Input Radio object



The HTML DOM Input radio object is associated with the <input> element with type “radio”. We can create and access an input element with type radio using the createElement() and getElementById() method respectively.

Properties

Following are the properties of the Input Radio object −

Sr.NoProperties & Description
1Autofocus
To set or return if the radio button should get focus automatically when the page loads or not.
2Checked
To set or return the radio button checked state.
3defaultChecked
To return the checked attribute default value for a radio button
4defaultValue
To set or return the radio button default value.
5Disabled
To set or return whether the radio button should e disabled, or not
6Form
To return the reference to the form containing the radio button
7Name
To set or return the name attribute value of a radio button.
8Required
To set or return if it’s mandatory to check a radio button before submitting the form.
9Type
To return the form element type for the radio button.
10Value
To set or return the value of the value attribute of the radio button.

Syntax

Following is the syntax for −

Creating an input radio object.

var R = document.createElement(“INPUT");
R.setAttribute("type", "radio");

Example

Let us look at an example of the Input radio object −

Live Demo

<!DOCTYPE html>
<html>
<head>
<script>
   function createRadio() {
      var R = document.createElement("INPUT");
      R.setAttribute("type", "Radio");
      document.body.appendChild(R);
   }
</script>
</head>
<body>
<h1>Input radio object</h1>
<p>Create an input field with type radio by clicking the below button</p>
<button type=”button” onclick="createRadio()">CREATE</button>
<br><br>
Mango:
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button −

In the above example −

We have created a button CREATE that will execute the createRadio() method when clicked by the user −

<button type=”button” onclick="createRadio()">CREATE</button>

The createRadio() method uses the createElement() method of the document object to create the <input> element by passing “INPUT” as a parameter. The newly created input element is assigned to variable R and using the setAttribute() method we create a type attribute with value radio.

Remember, setAttribute() creates the attribute and assigns value if the attribute doesn’t exist previously. Finally, using the appendChild() method on document body we append the input element with type radio as the child of the body −

function createPASS() {
   var R = document.createElement("INPUT");
   R.setAttribute("type", "Radio");
   document.body.appendChild(R);
}

Advertisements