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);
Related
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>
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().
I am trying to create a form which will take the user input to create a query for database. I have three buttons: And, Or, Run.
I am creating dynamic elements on click of buttons And and Or.
The div search_list is the container for containing the elements.
I need the form to be submitted on click of Run.
The weird thing is, whenever I click on any button the form gets submitted. How do I stop it ? Please let me know If you need more info.
Thanks
<html>
<head>
<script type="text/javascript">
var count = 0;
function loadfirst(){
count=1;
addFilter('');
}
function addFilter(flag){
var div = document.querySelector("#search_list");
tr = document.createElement("tr");
select = document.createElement("select");
var sear_value = document.createElement("input");
var and_or = document.createTextNode(flag);
tr.id='tr_'+count;
select.id='sl_'+count;
sear_value.id='sear_value_'+count;
select.options.add( new Option("user id","user_id", true,true) );
select.options.add( new Option("First name","first_name"));
select.options.add( new Option("Last name","last_name"));
select.options.add( new Option("Course","course"));
sear_value.type="text";
if(count<=1){
var bt_and= document.createElement("button");
bt_and.id='and';
var bt_label = document.createTextNode("And");
bt_and.appendChild(bt_label);
bt_and.addEventListener('click', function() {
addFilter('and');
return false;
});
var bt_or= document.createElement("button");
bt_or.id='or';
var bt_label = document.createTextNode("Or");
bt_or.appendChild(bt_label);
bt_or.addEventListener('click', function() {
addFilter('or');
return false;
});
}
else{
var bt_rem= document.createElement("button");
bt_rem.id='rem_'+count;
var bt_label1 = document.createTextNode("x");
bt_rem.appendChild(bt_label1);
var tr_id = 'tr_'+count;
bt_rem.addEventListener('click', function() {
var element= document.getElementById(tr_id);
element.parentNode.removeChild(element);
return false;
});
}
tr.appendChild(and_or);
tr.appendChild(select);
tr.appendChild(sear_value);
if(count<=1){
tr.appendChild(bt_and);
tr.appendChild(bt_or);
}
else{
tr.appendChild(bt_rem);
}
div.appendChild(tr);
count++;
}
function getFilter(){
alert();
}
</script>
</head>
<body onload="loadfirst()">
<span id='manage_stud_header' class= 'list_header'>
<label><?php echo $module_name;?></label>
<center>
<form>
<div id='search_list' class='search'></div>
<button id="run_filter" type="submit">Run</button>
</form>
</center>
</span>
</body>
</html>
The default type for buttons is "submit", so you have to explicitly say you want a plain button:
var bt_and= document.createElement("button");
bt_and.type = "button";
This way it won't submit the form when clicked. (unless of course you tell it to :))
you have to change
<button id = "run_filter" type = "submit" > Run </button>
in
<input id = "run_filter" type = "submit" value="Run" />
and then if the behaviour of click on button is forced to reload the page try to change button on other form element or see e.preventdefaulT of jquery
This question already has answers here:
JavaScript DOM remove element
(4 answers)
Closed 8 years ago.
my html div part is
<div id="upload">
<input type="button" id="add" value="Click here to add" onclick="uploadFile();">
<input type="hidden" name="fileCount" id="fileCount" value="0" />
</div>
my javascript is
function uploadFile()
{
var count = parseInt($('#fileCount').val(), 10);
count = count + 1;
if(count<=2){
var x = document.createElement("INPUT");
var br = document.createElement("br");
var text = document.createElement("INPUT");
var remove = document.createElement("INPUT");
text.setAttribute("type", "text");
text.setAttribute("name", "description_" + count);
text.setAttribute("value", "file description");
remove.setAttribute("type", "button");
remove.setAttribute("value", "Delete");
remove.setAttribute("id", "Delete"+count);
remove.setAttribute("onclick", "remove();");
x.setAttribute("type", "file");
x.setAttribute("name", "file_" + count);
x.setAttribute("id", "file_" + count);
x.setAttribute("onchange","checkFile(this);");
upload.appendChild(br);
upload.appendChild(x);
upload.appendChild(text);
upload.appendChild(remove);
$('#fileCount').val(count);
}
else{
alert("cant upload more than two files");
}
}
function remove()
{
// upload.getElementById(file_).remove();
}
Here I need a remove function for deleting the corresponding element when I click Delete button dynamically.
call this function on click of the button.
function removeDummy() {
var elem = document.getElementById('elementtodelete');
elem.parentNode.removeChild(elem);
return false;
}
You can use jQuery remove() method which delete the elements from HTML and DOM.
$(selector).remove();
jQuery remove method ref: remove()
Here's a demo of what I'm talking about - http://jsfiddle.net/MatthewKosloski/qLpT9/
I want to execute code if "Foo" has been clicked, and a number has been entered in the input.. and if "send" has been clicked.
<h1>Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="send">Send</button>
I'm pretty sure I'm overthinking this, I'd appreciate the help on such a concise question.
try this one: jfiddle link
var send = document.getElementById("send");
var h1 = document.getElementsByTagName("h1");
var foo_clicked = 0;
h1[0].onclick = function(){foo_clicked += 1; };
send.onclick = function(){
if(document.getElementById("amount").value !='' && foo_clicked >0 )
alert ('poor rating');
};
As per your statement & taking some assumptions, try this way:
(This executes function twice - When there is a change of text or a click of the button).
HTML:
<h1 id="">Foo</h1>
<input type="text" id="amount" placeholder="Enter in a number."/>
<button id="sendBtn">send</button>
JS:
document.getElementById("amount").addEventListener("change",poorRatingCalculation);
document.getElementById("sendBtn").addEventListener("click",poorRatingCalculation);
function poorRatingCalculation() {
var rating = document.getElementById("amount").value;
if(rating=="poor") alert("Poor Service");
}
DEMO: http://jsfiddle.net/wTqEv/
A better, self contained example:
http://jsfiddle.net/qLpT9/7/
(function()
{
var clicked = false;
var header = document.getElementById("header");
var amount = document.getElementById("amount");
var send = document.getElementById("send");
header.addEventListener("click", function()
{
clicked = true;
});
send.addEventListener("click", function()
{
if(!clicked)
{
return
}
// Foo has been clicked
var value = amount.value;
console.log(value;)
});
})();
Is this what you were looking for?
http://jsfiddle.net/qLpT9/5/
function poorRatingCalculation(){
if(myInput.value) {
alert(myInput.value);
}
}
var foo = document.getElementById("foo"),
myInput = document.getElementById("amount");
foo.addEventListener("click", poorRatingCalculation, false)