I want to create a button that creates another button. The other button get an id attribute by counting from 1 to infinity. This functionality should done on all buttons (original button and the news).
var btn = document.createElement("input");
btn.type = "button"
btn.value = "button"
btn.id = "btn_rv"
body.appendChild(btn);
function create_another_button(elm) {
var counter = parseInt(elm.getAttribute('data-counter'));
var button = document.createElement('button');
button.innerText = elm.id + '_' + counter;
button.id = elm.id + '_' + counter;
button.setAttribute('data-counter', '1');
button.setAttribute('onclick','create_another_button(this)');
document.body.appendChild(button);
elm.setAttribute('data-counter', ++counter)
}
<button id="btn_rv" onclick="create_another_button(this)" data-counter="1">Main Button</button>
http://jsbin.com/tuwoxe/edit?html,css,js
I do not get the use case, but this should be what you are looking for:
var btn = document.createElement("input");
var countBtn;
btn.type = "button";
btn.value = "button";
btn.id = "btn_rv";
document.body.appendChild(btn);
btn.addEventListener('click', function(){
if (!countBtn){
countBtn = document.createElement("input");
countBtn.type = "button";
countBtn.value = 0;
countBtn.id = "btn_rv";
document.body.appendChild(countBtn);
}
else{
countBtn.value++;
}
}, false);
Check it out at https://jsfiddle.net/ugyknfc0/
if you want to fire another button , try this code
<input type="button"
id="BtnId"
onclick="fireButton();addButton();" />
Function 1 for firing the Button
function fireButton()
{
document.getElementById('btn_rv_1').click()
}
Function 2 for adding the Button
function addButton()
{
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var place= document.getElementById("SpanID");
//Append the element in page (in span).
place.appendChild(element);
}
In HTML
<span id="SpanID"> </span>
If you wish you can try this.
html
<body>
<div id="top">
<button id="button_1">Button 1</button>
</div>
<script type="text/javascript" src="func.js"></script>
</body>
func.js
var bid = 2;
document.getElementById("button_1").addEventListener("click", function () {
add_button(bid);
add_event_listener(bid);
bid += 1;
});
function add_button(button_id) {
var div = document.getElementById("top");
div.innerHTML = div.innerHTML + "<button id='button_" + button_id + "'>Button " + button_id + "</button>";
}
function add_event_listener(button_id) {
document.getElementById("button_" + button_id).addEventListener("click", function () {
add_button(bid);
add_event_listener(bid);
++bid;
});
}
Related
i am creating a todo list as a beginner exercise to train my JS skills but i hit a wall (again). As you can see in my code, i can create tasks that need doing and to each task i appended 2 buttons. Now i want both buttons to do the same thing (remove the task). I would like to create a addEventListener to those buttons but since i created them through JS and not HTML i don't now how to access them or their behavior (i don't know how to get their ID or if they even have one). So my question is this: how can i access those buttons through JavaScript? Thanks.
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Todo.css">
<title>ToDo App</title>
<script src='todo.js' defer></script>
</head>
<body>
<h1>To-Do List</h1>
<form id="Listcreator" name="itemAdd">
<input id="listItem" type="text">
<button id="addItem" type="submit"> Ajouter </button>
<button id="resetList" type="submit"> Tout Enlever</button>
</form>
<ul id="laListe"> </ul>
</body>
var buttons = document.createElement('button');
buttons.innerHTML = "X";
buttons.addEventListener("click", function(){
this.parentNode.remove();
});
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
buttons2.addEventListener("click", function(){
this.parentNode.remove();
});
You can add an event listener to your buttons when they are created.
https://jsfiddle.net/cnsxaL3b/
After adding event listeners, your code should look like below:
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
// Event listener for first button
buttons.addEventListener('click', function() {
alert('clicked button1');
});
// Event listener for first button
buttons2.addEventListener('click', function() {
alert('clicked button2');
});
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};
enter image description hereI have a button that permit to add checkbox element dynamically,
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
check.setAttribute('type', 'checkbox')
check.setAttribute('name', 'check')
form.appendChild(checkinput)
}
I want to count how many the user created a new Element whenever he presses the button
var count=0;
function addCheck() {
let pos= document.getElementById("dynamic-checkbox");
var checkinput = document.createElement("input");
check.setAttribute("type", "checkbox");
check.setAttribute("name", "rep");
pos.appendChild(check);
count++;
Here's an alternative to using a counter variable, or checking the length of the number of existing elements in the DOM. You initially set up the counter element with the textContent set as zero, and then with each call of the function set that content to whatever the current content is (coerced from a string to a number) plus 1.
// Cache the elements we reuse
const form = document.querySelector('form');
const button = document.querySelector('button');
const counter = document.querySelector('#counter');
button.addEventListener('click', addCheck, false);
function addCheck() {
const checkinput = document.createElement('input');
checkinput.setAttribute('type', 'checkbox');
checkinput.setAttribute('name', 'check');
form.appendChild(checkinput);
counter.textContent = Number(counter.textContent) + 1;
}
<div id="counter">0</div>
<button>Add checkbox</button>
<form></form>
You can use querySelectorAll() by passing the input type as the selector and take the length:
var count = form.querySelectorAll('input[type=checkbox]').length;
var form= document.getElementById("form");
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
var count = form.querySelectorAll('input[type=checkbox]').length;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
You can also maintain a variable as counter:
var form= document.getElementById("form");
var count = 0;
function addCheck() {
var checkinput = document.createElement("input");
checkinput.setAttribute("type", "checkbox");
checkinput.setAttribute("name", "check");
form.appendChild(checkinput);
count++;
console.log('Total Checkbox: ' +count);
}
<form id="form"></form>
<button type="btn" onclick="addCheck()">Add</button>
Just add a counter and increment it on button click. While setting attribute you have used the name of the variable in which the element is stored as check, but it should be checkinput
var count = 0;
var total=0;
function addCheck() {
var checkinput = document.createElement('input')
var form = document.getElementById('form')
checkinput.setAttribute('type', 'checkbox')
checkinput.setAttribute('name', 'check')
form.appendChild(checkinput)
count++;
total=count+2;
console.log('Number of checkboxes created by the user:' + count)
console.log( 'Total checkboxes in the form:' + total)
}
<button onclick="addCheck()">click</button>
<form id="form">
<input type="checkbox" name="check">
<input type="checkbox" name="check">
</form>
I am trying to create a checkbox with javascript when a button is clicked. I am really struggling, I have searched the net for help and this is the closest I've got but it does not work.
What have I done wrong?
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="check" name="checkBoxes">
<script>
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array( )
check_value[0] = "Yellow"
check_value[1] = "Red"
check_value[2] = "Green"
for(var count in check_value)
{
var color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
ColorsAvailable.appendChild(color);
}
}
</script>
After you add an element that has an id of checkBoxes and some semicolons ; the code actually works.
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array();
check_value[0] = "Yellow";
check_value[1] = "Red";
check_value[2] = "Green";
var color, p, br;
for(var count in check_value)
{
color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
p =document.createElement("span");
p.innerHTML = check_value[count] + ": ";
br =document.createElement("br");
ColorsAvailable.appendChild(p);
ColorsAvailable.appendChild(color);
ColorsAvailable.appendChild(br);
}
}
input[type='checkbox']
{
margin-right:20px;
}
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="check" name="checkBoxes">
<div id="checkBoxes"></div>
The id of the input was check and not checkBoxes. I changed it and also you can't directly append in the input so I made it append in the parent node but you could change to be on another place.
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="checkBoxes" name="checkBoxes">
<script>
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array( )
check_value[0] = "Yellow"
check_value[1] = "Red"
check_value[2] = "Green"
for(var count in check_value)
{
var color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
ColorsAvailable.parentNode.appendChild(color);
}
}
</script>
Make checkboxes a DIV.
<div id="check" name="checkBoxes"></div>
and change this
var ColorsAvailable = document.getElementById('check');
I've created some code that dynamically creates some fields within a SPAN element. One of the fields is a delete icon, that when click runs a function to remove the selected span. Now I want to create a function that simply wipes out all the spans, sounds simple but it breaks after the first one.
This is a sample of my code (modified it for simplicity):
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ip = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ip.setAttribute("type", "text");
ip.setAttribute("value", item)
ip.setAttribute("Name", "text_item_element_" + global_i);
ip.setAttribute("id", "id_item_" + global_i);
ip.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ip);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
In each line for the image I set the onclick event handler to run the function removeSpanElement(parentDiv, childDiv) and it works fine. So to clear them all I'd think I just run the function through an incremental loop, clearItems(), but it stops after removing the first one and I can't figure out why.
You can simply add a new class to the dynamically added span(to make it easy to select them), then remove all the elements with the added class like
var global_i = 0; // Set Global Variable i
function increment() {
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem() {
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ins = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ins.setAttribute("type", "text");
ins.setAttribute("value", item);
ins.setAttribute("Name", "text_item_element_" + global_i);
ins.setAttribute("id", "id_item_" + global_i);
ins.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ins);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
el.className = 'dynamic'
document.getElementById("myForm").appendChild(el);
}
/* This function only clears 1st span */
function clearItems() {
var spans = document.getElementsByClassName('dynamic');
while (spans.length) {
spans[0].remove();
}
global_i = 0;
}
<form>
<input type='text' id='item' value='' />
<input type="button" value="Add" onclick="addItem()" />
<input type="button" value="Clear All" onclick="clearItems()" />
<span id="myForm"></span>
</form>
You were using a reserved keyword, and you were having a variable undefined. I've edited the code for you. Compare my code with yours to see where are the mistakes.
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem(){
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ig = document.createElement("INPUT"); // "in" is a reserved keyword. It can't be used as a variable
var ip = document.createElement("IMG");
var el = document.createElement('SPAN');
ig.setAttribute("type", "text"); // modified
ig.setAttribute("value", item) //
ig.setAttribute("Name", "text_item_element_" + global_i); //
ig.setAttribute("id", "id_item_" + global_i); //
ig.setAttribute("style", "width:80px"); //
ig.setAttribute("src", "delete.png"); // "im" was undefined. You probably wanted to write "in", but it was wrong anyway
ig.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')"); // the same
el.appendChild(ig);
el.appendChild(ig);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
<code> <form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
try{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var in_e = document.createElement("INPUT");
var ip_e = document.createElement("IMG");
var el = document.createElement('SPAN');
in_e.setAttribute("type", "text");
in_e.setAttribute("value", item)
in_e.setAttribute("Name", "text_item_element_" + global_i);
in_e.setAttribute("id", "id_item_" + global_i);
in_e.setAttribute("style", "width:80px");
ip_e.setAttribute("src", "delete.png");
ip_e.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(in_e);
el.appendChild(in_e);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}catch(e){alert(e)}
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
</code>
I have two buttons and a counter, I have to reset counter every time I change the button. I don't know how to reset the counter.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
clickCount();
count=0;
}
button2.onclick = function(){
clickCount();
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Pass a parameter to your clickCount function with the button name, and check if it has changed.
var count = 0;
var lastButtonClicked = "";
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(buttonName){
if (buttonName === lastButtonClicked)
{
count++;
}
else
{
count = 1;
lastButtonClicked = buttonName;
}
display.innerHTML = count;
}
button1.onclick = function(){
clickCount("1");
}
button2.onclick = function(){
clickCount("2");
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
Just add the extra parameter that determines which button the counter is from.
var isFirstButton = true;
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
function clickCount(){
count++;
display.innerHTML = count;
}
button1.onclick = function(){
if (!isFirstButton){
count = 0;
}
isFirstButton = true;
clickCount();
}
button2.onclick = function(){
if (isFirstButton){
count = 0;
}
isFirstButton = false;
clickCount();
}
I updated your original code, added a active button variable which is chosen from the event target, this way, it doesn't matter how many buttons you want to count, they will all be unique, and you don't need a variable for each one.
This is similar to [stephen.vakil] post, however with this code, you do not need to name the buttons, just use the DOM and event target to define the uniqueness.
var count = 0;
var button1 = document.getElementById("Button1");
var button2 = document.getElementById("Button2");
var display = document.getElementById("displayCount");
var activeTarget; // which target are we counting
function clickCount(e){
var e = e || window.event; // IE or other browser event
var target = e.target || e.srcElement; // target from different browsers
if(target != activeTarget) { // Is this the current target?
count = 0; // No, reset counter
activeTarget = target; // and make it the active target
}
count++; // No matter which target, incr counter
display.innerHTML = count; // and display result
}
button1.onclick = function(e) { // don't forget the event arg
clickCount(e); // and pass it to the count function
}
button2.onclick = function(e) { // same as above
clickCount(e);
}
<input type="button" value="button1" id="Button1" />
<input type="button" value="button2" id="Button2" />
<p>Clicks: <span id="displayCount">0</span> times.</p>
The reference for the source event target onclick calling object