displaying dynamically created radio buttons with line breaks - javascript

I have some code to dynamically create radio buttons on an html page using javascript. Where and how can I perhaps add a "<br>" in order to have the radio buttons display one per line on the resulting html page?
Please take a look at the jsfiddle via the link below.
http://jsfiddle.net/kevalbhatt18/owuqm8j8/
var radio_home = document.getElementById("radio_home");
function makeRadioButton(options) {
var div = document.createElement("div");
for (var i = 0; i < options.length; i++) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = options[i].name;
radio.value = options[i].value;
label.appendChild(radio);
label.appendChild(document.createTextNode(options[i].text));
div.appendChild(label);
}
radio_home.appendChild(div);
}
var options = [{
name: "first",
value: "yes",
text: "yes"
}, {
name: "first",
value: "no",
text: "no"
}]
var options2 = [{
name: "second",
value: "ohhh yes",
text: "ohhh yes"
}, {
name: "second",
value: "ohhh no",
text: "ohhh no"
}]
makeRadioButton(options);
makeRadioButton(options2);
<div id="radio_home"></div>

To add a <br> tag you simply use the document.createElement function as you did for the radioubuttons and apend it straight after
function makeRadioButton(options) {
var div = document.createElement("div");
for (var i = 0; i < options.length; i++) {
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = options[i].name;
radio.value = options[i].value;
label.appendChild(radio);
label.appendChild(document.createTextNode(options[i].text));
div.appendChild(label);
//if we are on the last itteration there is no need to create another <br>
if(i+1<options.length)div.appendChild(document.createElement('br'));
}
radio_home.appendChild(div);
}
Updated demo

To achieve the desired results, you do not even need <br>. Just create div inside the for loop and append it to the containing parent inside the loop only. You need to update your function to following
function makeRadioButton(options) {
for (var i = 0; i < options.length; i++) {
var div = document.createElement("div"); // moved inside the loop
var label = document.createElement("label");
var radio = document.createElement("input");
radio.type = "radio";
radio.name = options[i].name;
radio.value = options[i].value;
label.appendChild(radio);
label.appendChild(document.createTextNode(options[i].text));
div.appendChild(label);
radio_home.appendChild(div); // moved inside the loop
}
}
For reference - http://jsfiddle.net/owuqm8j8/2/

If you are only looking for displaying the radio buttons one below the other, you can probably make use of the display property of css and add it to the label. Hers is the updated fiddle, code below:
label
{display:block;}

Related

Is there a reason why my check mark box won't be selected when I click the span tag?

//init function
function init() {
createTaskElements();
}
//create elements and add them to the unordered list
//set attributes
function createTaskElements() {
const arrChores = ["Walk the dog", "Set dinner table", "Load dishwasher", "Empy Dishwasher", "Clean dinner plates"];
for (var i = 0; i < arrChores.length; i++) {
var task = document.createElement("LI");
task.id = "task";
var input = document.createElement("INPUT");
input.type = "checkbox";
input.id = "chore";
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
span.addEventListener("click", crossClick);
task.appendChild(input);
task.appendChild(span);
task.addEventListener("click", crossOut);
document.getElementById("itemsList").append(task);
}
}
//set the class name of the list item whenever it is clicked to completed
function crossOut() {
this.className = "completed";
}
function crossClick() {
}
W
hat I want to do when I click the span tag it checks the check box next to the element, but it isn't working.
I know the .checked method, but I'm not sure how I would get my function to work.
Replace
var span = document.createElement("SPAN");
span.innerHTML = arrChores[i];
with
const label = document.createElement("label");
label.textContent = arrChores[i];
label.htmlFor = input.id;
You don't need to add any Javascript behaviour to that label as it already comes with the functionality you ask for.

Check box won't append

So the HTML has these elements, there can be a random number of them. I would simply like to create a check box, and add it to each element with the class name "username".
So when a new element with the class "username" gets created or when the page is opened. It'll add a check box to it.
Here's my script.
var chec = document.createElement("div"); //Creates the div..
chec.innerHTML = '<input type="checkbox" value="test">'; //Create checkbox
var addc = document.querySelector("span[class='username']") // username Element.
var i;
for (i = 0; i < addc.length; i++) {
chec += addc[i];
}
It doesn't add the check boxes. Can someone help me understand why and possibly help me with my script.
var addc = document.querySelectorAll("span.username") // Get all elements with class "username"
for (var i = 0; i < addc.length; i++) {
var div = document.createElement("div");
var check = document.createElement("input");
check.type = "checkbox";
check.value = "test";
div.appendChild(check);
addc[i].appendChild(div);
}
<span class="username"></span>
<span class="username"></span>
<span class="username"></span>

How do I add an onchange attribute to a JavaScript generated checkbox that fires when checked/unchecked?

I have a large json list of people, they just have an id and a name.
Below I'm looping through it and it's working fine adding a list of checkboxes.
I have another one similar but with a shorter json list and the code's the same so it's not an issue with the json but the way I'm writing my js code.
I'm doing the below.
Creating checkboxes & labels, for each person in obj.people...
var peopleLen = obj.People.length;
for (var i = 0; i < peopleLen; i++) {
if (i < obj.People.length) {
checkbox = null;
label = null;
linebreak = null;
linebreak = document.createElement('br');
checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = "target";
checkbox.value = obj.People[i].ID;
checkbox.id = "cbTarget" + i.toString();
label = document.createElement('label');
label.id = "lbTarget" + i.toString();
label.htmlFor = "cbTarget" + i.toString();
//This is where I believe it's wrong:
checkbox.onclick = function () {
toggleTargetList(obj.People[i].ID);
};
label.appendChild(document.createTextNode('\u00A0\u00A0' + obj.People[i].Name));
document.getElementById("divcbTargets").appendChild(checkbox);
document.getElementById("divcbTargets").appendChild(label);
//Add a line break:
document.getElementById("divcbTargets").appendChild(linebreak);
}
}
The function I'm assigning to it is:
function toggleTargetList(t) {
alert(t);
}
A simple alert.
When I change:
toggleTargetList(obj.People[i].ID);
To:
toggleTargetList(obj.People[0].ID);
It alerts correctly displaying the first person's id, however when it's [i] it alerts the same value (the first value of the json object's people's id property).
I don't see why this is acting up.
It's alerting on assigning the checkbox attribute and not when the actual checkbox is clicked which is another issue.
checkbox.onclick = function () {
toggleTargetList(obj.People[i].ID);
};
The variable i is outside of the scope of the callback function.
Conveniently though you are already assigning the value of obj.People[i].ID to the checkboxes .value property.
checkbox.value = obj.People[i].ID;
So simply use this like:
checkbox.onclick = function(event) {
toggleTargetList(event.target.value);
};
Try out as
var obj = {
People: [{
ID: 1,
name: 'Manish'
}, {
ID: 2,
name: 'Manish'
}, {
ID: 3,
name: 'Manish'
}, {
ID: 4,
name: 'Manish'
}, {
ID: 5,
name: 'Manish'
}]
};
var peopleLen = obj.People.length;
for (var i = 0; i < peopleLen; i++) {
if (i < obj.People.length) {
checkbox = null;
label = null;
linebreak = null;
linebreak = document.createElement('br');
checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = "target";
checkbox.id = "cbTarget" + i.toString();
// I have added this code
checkbox.ID = obj.People[i].ID;
checkbox.onclick = function() {
toggleTargetList(this.ID);
};
label = document.createElement('label');
label.id = "lbTarget" + i.toString();
label.innerText = "cbTarget" + i.toString();
label.appendChild(document.createTextNode('\u00A0\u00A0' + obj.People[i].name));
document.getElementById("divcbTargets").appendChild(checkbox);
document.getElementById("divcbTargets").appendChild(label);
document.getElementById("divcbTargets").appendChild(linebreak);
}
}
// I have added this code
function toggleTargetList(index) {
alert(index);
}
<div id="divcbTargets"></div>
Also you can have similar onchange event for that.

Not able to replace checkboxes Javascript

I am creating a mozilla add on for a web page. Using the attached Javascript code I am able to create checkbox. The checkbox should replace with other checkbox depending on the selected value in dropdown. Onclick on dropdown I am calling fun_sub_cat function which is creating checkbox and also replacing but it replace only once. For eg: If there are 2 option in dropdown 1 and 2, Selecting option 1 checkbox values should 1,2,3 and for option 2 checkbox values should be a,b,c.
On Click function it creates checkbox and changing the value for the first time replaces the checkbox value as well however when I click 3rd time on dropdown or change the value, it does not work. It attains the 2nd time changed checkbox values.
var k = 0;
function fun_cat_sub() {
console.log("Value Changed");
var Myarry = "";
if(document.getElementById('sub_cat').value == 'Password Reset'){
Myarry = check_list1;
if(k == 0){
console.log("creating checkbox for the first time");
k = k+1;
for (var i = 0; i < Myarry.length; i++) {
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.id = "checkBox"+i;
checkbox.value = Myarry[i];
checkbox.class = "_class";
checkbox.appendAfter(br_3);
var lab_chk = document.createElement('label');
lab_chk.innerHTML = Myarry[i];
lab_chk.id = "lab_chk"+i;
lab_chk.value = Myarry[i];
lab_chk.style.marginLeft = "10px";
lab_chk.appendAfter(checkbox);
document.createElement('br').appendAfter(lab_chk);
}
}
else if(k != 0){
console.log("I am in 1st Loop");
checking(Myarry);
}
}
else {
Myarry = check_list2;
console.log("I am in 2nd Loop");
checking(Myarry);
}
}
function checking(Myarry){
console.log(Myarry.length);
for (var i = 0; i < Myarry.length; i++) {
var old_chk = document.getElementById('checkBox'+i);
var new_chk = document.createElement("input");
new_chk.type = "checkbox";
new_chk.id = "checkBox"+i;
new_chk.value = Myarry[i];
old_chk.parentNode.replaceChild(new_chk, old_chk);
var old_lab_chk = document.getElementById('lab_chk'+i);
var new_lab_chk = document.createElement('label');
new_lab_chk.innerHTML = Myarry[i];
new_lab_chk.style.marginLeft = "10px";
old_lab_chk.parentNode.replaceChild(new_lab_chk, old_lab_chk);
}
}

radio button doesn't come up from JS file

The issue is the radio button didn't come up. And I am confused with the concept of create node, create node text, create node value, createElement, etc. those kind of concepts.
Here is my code, http://jsfiddle.net/vadjn2an/
Here is my function,
function displayQuestion() {
var question = document.getElementById("question");
question.textContent = questionPool[currentQuestion].question;
var numberOfChoices = questionPool[currentQuestion].choices.length;
for(var i=0; i < numberOfChoices; i++) {
var label = document.createElement('label');
var radio = document.createElement('input');
radio.setAttribute('type', 'radio');
radio.setAttribute('name', 'choice');
radio.setAttribute('value', 'questionPool[currentQuestion].choices[i]');
label.appendChild(radio);
question.appendChild(label);
label.innerHTML = questionPool[currentQuestion].choices[i] + "<br>";
}
Thanks for your help in advance,
Try below code.
createTextNode
var questionPool = [
{
question: " Which is the biggest city in China?",
choices: ["Beijing", "Shanghai", "Guangzhou"],
correctAnswer: 1,
}
];
var question = document.getElementById("question");
var questionPool = questionPool[0];
question.textContent = questionPool.question;
for(var i=0;i<questionPool.choices.length;i++){
var label = document.createElement('label');
var radio = document.createElement('input');
radio.setAttribute('type', 'radio');
radio.setAttribute('name', 'choice');
radio.setAttribute('value', questionPool.choices[i]);
label.appendChild(radio);
var txt = document.createTextNode(questionPool.choices[i]);
label.appendChild(txt);
question.appendChild(label);
}
Here is the complete answer to your question. The HTML part
<form>
<label id="question">Question:</label><br />
<div id="answersBox">
</div>
<input type="button" value="save" />
</form>
The Javascript part
var questionPool = [
{
question: " Which is the biggest city in China?",
choices: ["Beijing", "Shanghai", "Guangzhou"],
correctAnswer: "Beijing",
}
];
var currentQuestion = questionPool[0].question;
document.getElementById('question').innerHTML = currentQuestion;
choiceList();
function choiceList() {
var question=questionPool[0];
for (choice in question.choices) {
var choiceSelection = document.createElement('input');
var choiceLabel = document.createElement('label');
choiceSelection.setAttribute('type', 'radio');
choiceSelection.setAttribute('name', 'choice');
choiceLabel.innerHTML=question.choices[choice];
choiceLabel.setAttribute('for', question.choices[choice]);
document.getElementById('answersBox').appendChild(choiceSelection);
document.getElementById('answersBox').appendChild(choiceLabel);
}
}
choiceList();
The reason it won't show up is because you replace label's innerHTML into
questionPool[currentQuestion].choices[i] + <br>.
when you append radio into label,label's innerHTML become "<input>...</input>"
but then you just replace it into
questionPool[currentQuestion].choices[i] + "<br>".
simple move the
label.innerHTML= ...
up before
label.appendChild can solve your situation.
here's a slightly modify answer without using innerHTML and outerHTML.
function displayQuestion() {
var question = document.getElementById("question"),
currentQuestion = 0,
numberOfChoices = questionPool[currentQuestion].choices.length;
question.textContent = questionPool[currentQuestion].question;
question.appendChild(document.createElement('br'));
for(var i=0; i < numberOfChoices; i++) {
var label = document.createElement('label'),
radio = document.createElement('input'),
textNode= document.createTextNode(questionPool[currentQuestion].choices[ i]),
lineBreakNode = document.createElement("br");
radio.setAttribute('type', 'radio');
radio.setAttribute('name', 'choice');
radio.setAttribute('value', 'questionPool[currentQuestion].choices[i]');
label.appendChild(radio);
label.appendChild(textNode);
label.appendChild(lineBreakNode);
question.appendChild(label);
}
}
http://jsfiddle.net/vadjn2an/9/
to have radio show before label, I use label.outerHTML to inject it as label's innerHTML
function displayQuestion() {
var question = document.getElementById("question");
var currentQuestion = 0;
var numberOfChoices = questionPool[currentQuestion].choices.length;
question.textContent = questionPool[currentQuestion].question;
question.appendChild(document.createElement('br'));
for(var i=0; i < numberOfChoices; i++) {
var label = document.createElement('label');
var radio = document.createElement('input');
radio.setAttribute('type', 'radio');
radio.setAttribute('name', 'choice');
radio.setAttribute('value', 'questionPool[currentQuestion].choices[i]');
label.innerHTML = radio.outerHTML + questionPool[currentQuestion].choices[i] + "<br/>";
question.appendChild(label);
}
}
http://jsfiddle.net/vadjn2an/8/
You need to append the radio button to question, please change the code line
from
label.appendChild(radio);
to
question.appendChild(radio);
Hope this helps!

Categories

Resources