How to select a radio button by default in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

To select a radio button by default we have to check it as true. If it is checked as true then by default it will be autofocused

In the following example, we have only radio buttons and none of them is autofocused.

Example

Live Demo

<html>
   <form id="radiobuttons" name="radiobutton">
      <input id="rad1" value="a" type="radio" name="check"/>male
      <input id="rad2" value="b" type="radio" name="check"/>female
      <input id="rad3" value="c" type="radio" name="check"/>other
   </form>
<body>
</body>
</html>

When the above code is executed we will get radio buttons and none of them is autofocused as shown in the following image.

Output

To autofocus any of the above buttons we have to check them initially. This can be done by using pure javascript as shown in the following example.

Example

Live Demo

<html>
   <form id="radiobuttons" name="radiobutton">
      <input id="rad1" value="a" type="radio" name="check"/>male
      <input id="rad2" value="b" type="radio" name="check"/>female
      <input id="rad3" value="c" type="radio" name="check"/>other
   </form>
<body>
<script>
   radiobtn = document.getElementById("rad1");
   radiobtn.checked = true;
</script>
</body>
</html>

After executing the above code, we will get the following output.

Output

raja
Published on 04-Jul-2019 15:10:41
Advertisements