Dynamically add Radio Button Labels - JavaScript - javascript

Having trouble getting the a label dynamically assigned to a radio button. all of the code is working except the innerHTML. Cannot spot why. Thanks in advance for any help.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
</form>
<br>
<button onclick="addRadio()">Add radio buttons!</button>
<script>
// This function will add a new Radio buttons to the above
count = 0;
function addRadio()
{
count++;
//Create input type
var myRadio = document.createElement("input");
var myName = document.createElement("testRadio");
var myBreak = document.createElement("br");
var myLabel = document.createElement("label");
var labelMessage = "Radio Button: " + count;
var labelId = "l" + count;
myRadio.setAttribute("type", "radio");
myRadio.setAttribute("name", "testRadio");
myRadio.setAttribute("value", "Radio Button: " + count);
myLabel.setAttribute("for", labelId);
myRadio.setAttribute("id", labelId);
document.getElementById('myForm').appendChild(myRadio);
document.getElementById('myForm').appendChild(myLabel);
document.getElementById('myForm').appendChild(myBreak);
document.getElementById('labelId').innerHTML = 'labelMessage';
}
</script>
</body>
</html>

The label element might not be inserted by the next line itself. It is better to do
myLabel.innerHTML = 'labelMessage';
As you have the element already in a variable.

There is a tiny error in the code.
Before the .innerHTML you get the element by id 'labelId' as a string.
You need to select with the labelID as a var so:
document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;

Related

How to insert a created <input> tag into a created <p> tag with text?

I'm trying to put a created input tag between the text of a created p tag. My method returns [object HTMLInputElement]. I want to create a text field for users to write in.
I've tried
<!DOCTYPE html>
<html>
<body>
<script>
let PTag = document.createElement("p");
let Input = document.createElement("input");
Input.type = "text";
PTag.innerText = "SampleTextOne " + Input + " SampleTextTwo";
document.body.appendChild(PTag);
</script>
</body>
</html>
I'm still new to creating HTML elements and positioning them.
You inserting Html Object as text inside your p tag.
instead of innerText appendChild a created Html element inside a created tag to work correctly.
<!DOCTYPE html>
<html>
<body>
<script>
let PTag = document.createElement("p");
let Input = document.createElement("input");
Input.type = "text";
// PTag.innerText = "SampleTextOne " + Input + " SampleTextTwo";
PTag.appendChild(Input);
document.body.appendChild(PTag);
</script>
</body>
</html>
But it's better to create html elements without javascript like this
<input type="text" placeholder="enter text" />
<body>
<script>
let PTag = document.createElement("p");
let Input = document.createElement("input");
Input.type = "text";
PTag.innerHTML = "SampleTextOne ";
PTag.append(Input);
PTag.innerHTML += " SampleTextOne";
document.body.appendChild(PTag);
</script>
</body>

how to bind dynamically created button click events to dynamically created input in javascript?

I am very new to javascripts and trying to create a dynamic html form where there are multiple button, and each button click map to a corresponding form input. Here is my code:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
So, the user would input number of groups to create and click 'Go' button, then the code should dynamically generate the form with the number the user choose. Each group of the form includes a input textbox and a 'Generate' button. When the button is clicked, the input textbox will show "hello world". However, the "hello world" only show up in the last input textbox no matter which 'Generate' button I click. So I changed the onclick function of the button to:
button.onclick = function(){ alert(thisID);};
Then I found that thisID is always the id of the last input textbox no matter which 'Generate' button I click. I guess that is because the binding of the click event does not happen till the script is done when 'thisID' would always be its latest value.
Would anyone please help me to realize the functionality I want? Thank you very much!
You would need to wrap the code within the for loop in a separate function, passing in the value of i as a parameter. This would create a closure, creating a new execution scope for your code. Otherwise what is happening is that your var is being hoisted, and is not exclusive to each iteration of the for loop, so your DOM is reflecting only the last value it was assigned.
for (i=1;i<=number;i++){
(function (i) {
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
})(i);
}
You can check out an article on closures here:
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
EDIT: As one of your commenters mentioned, you can also set your vars to 'let' to achieve a similar effect. This is because let scopes the variable to the current code block, rather than being hoisted to the scope of the function, so each for loop iteration has a private let variable. It is still recommended to get a good understanding of closures and how they work, however.
Since you are already using JQuery, you can reduce some of the logic.
Let me know if this helps-
<html>
<head>
<title>Create Group</title>
</head>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(()=>{
var txtGroup='<input type="text" id="txt_group_{0}" value="">';
var btnGroup='<button id="btn_group_{0}" type="button">Click Me</button>';
var container=$('#container');
$('#generate_form').click((e)=>{
var groupCount=parseInt($('#number_of_groups').val());
var idToStart=$('#container').children('div').length+1;
for(let i=idToStart;i< idToStart+groupCount;i++){
var divGroup=`<div id="div_group_${i}">`+
txtGroup.replace('{0}',i)+
btnGroup.replace('{0}',i)+`</div>`;
container.append(divGroup);
$('#btn_group_'+i).on('click',(e)=>{
console.log('#txt_group_'+i);
$('#txt_group_'+i).val('Hello World');
});
}
});
});
</script>
<body>
<h2></h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"></div>
</body>
</html>

Radio form value not showing up?

I am a still a newbie so sorry for any mistakes. I have searched a lot and couldn't solve my problem. I dynamically created this radio input:
var radio_input = document.createElement('input');
radio_input.type = "radio";
radio_input.name = "test_input"
radio_input.value = "teeest";
radio_input.appendChild(my_form);
However I can't get the input value to show up. I get something similar to this:
(but one instead of 3)
I want to have "test" written in the left side of the input... Can someone help me?
As #RobertoLinare said in his comment, you can create a div and append the label:
var radio_input = document.createElement('input');
var label = document.createElement('label');
var div = document.createElement('div');
radio_input.type = "radio";
radio_input.name = "test_input"
radio_input.value = "teeest";
label.innerHTML = "Label";
document.getElementById("my_form").appendChild(div);
div.appendChild(label);
div.appendChild(radio_input);
<form id="my_form">
</form>
Html :
<form id="my_form"></form>
JS :
var myForm = document.getElementById("my_form");
// Clear previous contents of the container
while (myForm.hasChildNodes()) {
myForm.removeChild(myForm.lastChild);
}
var radio_input = document.createElement("input");
radio_input.type = "radio";
radio_input.name = "test_input";
radio_input.value = "teeest";
var label = document.createElement('label');
label.innerHTML = "Label Title ";
myForm.appendChild(radio_input);
myForm.appendChild(label);

How to create a simple input and output in pure Javascript

I'm new to Javascript and am trying to write code for a simple greeting. The user will have an input box to type their name in to and below a button for them to click that outputs a value of "Hello {name}!". If you could help me out I would appreciate it!
You could start doing something like this:
(function() {
// Creates <input id="myTextBox" type="text" />
var textBox = document.createElement("input");
textBox.id = "myTextBox";
textBox.type = "text";
// Creates <button id="myButton" type="button">Show</button>
var btnShow = document.createElement("button");
btnShow.id = "myButton";
btnShow.type = "button";
btnShow.innerHTML = "Show";
// When you click in the button, show the message.
btnShow.onclick = function showMessage() {
alert("Hello " + textBox.value + "!");
};
// Add created elements.
document.body.appendChild(textBox);
document.body.appendChild(btnShow);
})();
You can find more information about createElement function in this site: Document.createElement().

Removing items from a to do list using Javascript

Attempting my first Javascript project, playing around with DOM to make a To-Do List.
After adding an item, how do i get the 'Remove' button to function and remove the item + the remove button.
Furthermore, after a new entry is made, the list item still stays in the input field after being added. How can it be made to be blank after each list item.
And yes i know my code is kinda messy and there is most likely an easier way to create it but I understand it like this for now.
Any help is greatly appreciated. Thanks
JSFiddle Link : http://jsfiddle.net/Renay/g79ssyqv/3/
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
function addText(){
var input = document.getElementById('inputTask').value;
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
node.appendChild(removeTask);
}
You can simply assign event:
removeTask.addEventListener('click', function(e) {
node.parentNode.removeChild(node);
});
http://jsfiddle.net/g79ssyqv/6/
Edited the Fiddle... just try this
FiddleLink (Should work now, button and p-tag will be removed)
HTML
<p id="addTask"> <b><u> Tasks </u></b> </p>
<input type='text' id='inputTask'/>
<input type='button' onclick='addText()' value='Add To List'/>
JS
var row = 0;
function addText(){
var input = document.getElementById('inputTask').value;
if(input != "")
{
var node=document.createElement("p");
var textnode=document.createTextNode(input);
node.appendChild(textnode);
node.setAttribute("id","contentP"+row);
document.getElementById('addTask').appendChild(node);
var removeTask = document.createElement('input');
removeTask.setAttribute('type', 'button');
removeTask.setAttribute("value", "Remove");
removeTask.setAttribute("id", "removeButton");
removeTask.setAttribute("onClick", "deleterow("+ row +");");
node.appendChild(removeTask);
row++;
}
else
{
alert("Please insert a value!");
}
}
function deleterow(ID)
{
document.getElementById('contentP'+ID).remove();
}
Greetings from Vienna
Use this
// +your code
.....
node.appendChild(removeTask);
// + modify
removeTask.onclick = function(e){
var dom = this;
var p_dom = this.parentNode;
console.log(p_dom);
var parent_node = p_dom.parentNode;
parent_node.removeChild(p_dom);
}

Categories