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().
Related
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;
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>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
I'm trying to make code to ask for your name, which then says, "Hello, _____, my name is Dolly." Then three buttons appear with options of what to do to Dolly.
Is there any way I can add a function onclick of the spawned buttons to create a response accordingly? I apologize if it's a bit messy and not dry, I'm kinda new to this.
<body>
<p id="dolly"></p>
<div id="div1">
<h3 id="try" class="enterN">Please enter your name</h3>
<input type="text" id="name" value="" placeholder="Please enter your name">
<button id="submit" onclick="yourName()">Enter</button>
</div>
<script>
function yourName() {
var x = document.getElementById("name").value;
if (x.length != 0) {
document.getElementById("dolly").innerHTML = "Hello, " + x + ", My name is Dolly.";
var btn = document.createElement("BUTTON");
var t1 = document.createTextNode("Say Hello");
btn.appendChild(t1);
document.body.appendChild(btn);
var btn = document.createElement("BUTTON");
var t2 = document.createTextNode("Hug Dolly");
btn.appendChild(t2);
document.body.appendChild(btn);
var btn = document.createElement("BUTTON");
var t3 = document.createTextNode("Kill Dolly");
btn.appendChild(t3);
document.body.appendChild(btn);
$(document).ready(function(){
$("#div1").remove();
});
} else {
document.getElementById("dolly").innerHTML = "Please enter your name.";
}
}
</script>
</body>
Hi you can set attribute onclick and pass your function like this
var btn = document.createElement("BUTTON");
var t1 = document.createTextNode("Say Hello");
btn.setAttribute("onclick", "function1()");
btn.appendChild(t1);
document.body.appendChild(btn);
You can add a new event listener to the created buttons.
btn.addEventListener('click', function() {
// do some things
});
You can set the onclick property with javascript like this:
btn.addEventListener('click', function(event) {
// code to be executed on click
}
for each of the child buttons you create.
to add the onclick function you do:
btn.onclick = function() {};
so for the first button you'd do
var btn = document.createElement("BUTTON");
btn.onclick = function() {};
var t1 = document.createTextNode("Say Hello");
btn.appendChild(t1);
document.body.appendChild(btn);
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);
}
Here is my JSFiddle: http://jsfiddle.net/kboucheron/XVq3n/15/
When I start a list of items and I click on "Clear", I would like to text input be cleared as well.I'm not able to clear the fields
<input type="text" placeholder ="Add List" id="listItem"/>
<button id="addButton">add Item</button>
<button id="clearButton">Clear Items</button>
<ul id="output"></ul>
clearButton.addEventListener("click", function(e) {
var text = document.getElementById('listItem').value;
var addItem = document.getElementById('output');
addItem.innerHTML = '';
text.value = '';
});
Just need to make this change here:
var text = document.getElementById('listItem');
You had this:
var text = document.getElementById('listItem').value;
What you are doing is getting the value of the input text, when you actually want the input element.
Also here is the updated fiddle: http://jsfiddle.net/XVq3n/16/
you are referring in your code to input's value, replace
var text = document.getElementById('listItem').value
with
var text = document.getElementById('listItem')
Ok, it's a really simple (but easy to make) error. Try this change and it should work:
clearButton.addEventListener("click", function(e) {
var text = document.getElementById('listItem');
var addItem = document.getElementById('output');
addItem.innerHTML = '';
text.value = '';
});
Basically, you did .value one too many times. Hope that helps.