How to create textNode for radio button with JS?

Viewed 226

I am trying to make a radio button with JavaScript. It's easy with HTML i.e <input type="radio" name="sType" value="m">MALE, so far with JS I'm able to create <input type="radio" name="sType" value="m"> but I don't know how to create MALE text Node for it. Also I want to append this form in 3rd div element of body with id='user_input' so what should be it's DOM navigation? Here is my code:

document.getElementsById('user_input').childNodes[0].appendChild(f);
var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");

var radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);       
2 Answers

If you want to add a description to the radio button, you should create a label and insert the description of the radio there.

let f = document.createElement("form");

let radio1 = document.createElement("input"); //input element, text
radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");

let label = document.createElement('label');
label.textContent = "MALE";
f.appendChild(radio1);
f.appendChild(label);
document.body.appendChild(f)

You can also create a text node and append after input, but this is not recommended option:

//The same as above
let desc = document.createTextNode("MALE")

f.appendChild(radio1)
f.appendChild(desc);
document.body.appendChild(f)`

Fiddle: https://jsfiddle.net/dpu54as9/

Input tags are auto-enclosing tags and should not have any text. You need to use a label tag alongside (you can check this link), such as:

<input type="radio" name="sType" id="radio1" value="m"/>
<label for="radio1">MALE</label>

And to do so in your code, simply create a new label element, set its text and append to the form:

var f = document.createElement("form");
f.setAttribute("id", "myForm");
f.setAttribute('method',"post");
f.setAttribute('action',"ride_test.php");


var radio1 = document.createElement("input"); //input element, text
var label1 = document.createElement("label");
// link label to input through id
label1.setAttribute("for", "radio1");
label1.innerHTML = "MALE";

radio1.setAttribute("id","radio1");
radio1.setAttribute('type',"radio");
radio1.setAttribute('name',"sType");
radio1.setAttribute('value',"m");
f.appendChild(radio1);
f.appendChild(label1);

Note that the IDs are unique, meaning you can't have more than 1 id with the same name simultaneously on the DOM. The best way to achieve what you want is to change user_input to a class (which is not unique), and then append to DOM as follows:

document.body.getElementsByClassName('user_input')[2].appendChild(f);
Related