Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dynamically create a radio button in Javascript that works in all browsers?

Tags:

javascript

Dynamically creating a radio button using eg

var radioInput = document.createElement('input'); radioInput.setAttribute('type', 'radio'); radioInput.setAttribute('name', name); 

works in Firefox but not in IE. Why not?

like image 530
Patrick Wilkes Avatar asked Sep 23 '08 01:09

Patrick Wilkes


People also ask

How do I create a dynamic radio button in HTML?

createElement("input"); radioYes. setAttribute("type", "radio"); /*Set id of new created radio button*/

How radio button is implemented in JavaScript?

Introduction to the JavaScript Radio Button To create a radio button, you use the <input> element with the type radio . A group of radio buttons is called a radio group. In this example, all the radio buttons have the same name size but different values. Because of this, you can only select one radio button at a time.


1 Answers

Taking a step from what Patrick suggests, using a temporary node we can get rid of the try/catch:

function createRadioElement(name, checked) {     var radioHtml = '<input type="radio" name="' + name + '"';     if ( checked ) {         radioHtml += ' checked="checked"';     }     radioHtml += '/>';      var radioFragment = document.createElement('div');     radioFragment.innerHTML = radioHtml;      return radioFragment.firstChild; } 
like image 107
Prestaul Avatar answered Oct 07 '22 16:10

Prestaul