javascript DOM element counter - javascript

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>

Related

Repeating a div based on user input (JavaScript solution preferred)

Looking for the simplest implementation of the following problem:
I have a user input number field like:
<input type="number" id="numInput" name="numInput" value="1" onchange="myFunc()">
<div id="demo">*** TEST ***</div>
I want to replicate the #demo div based on the #numInput value entered by the user, e.g. if the user enters '5', there would be five #demo divs displayed on the page. At the moment, I'm using the following function:
function myFunc() {
var newArray = [];
var numInput = document.getElementById('numInput').value;
var x = document.getElementById('demo').innerHTML;
for(var i=0; i<numInput; i++) {
newArray.push(x);
}
document.getElementById('demo').innerHTML = newArray;
}
but this is adding to the existing array rather than outputting the exact number of divs based on user input. Please advise. Thanks.
There should not be multiple same id values.
function myFunc() {
let numInput = document.getElementById("numInput");
while (numInput.nextSibling) {
numInput.nextSibling.remove();
}
let numInputval = document.getElementById('numInput').value;
for(var i=numInputval; i>0; i--) {
var newDiv = document.createElement('div');
newDiv.setAttribute('id', 'demo' + i);
newDiv.innerHTML = '*** TEST ***';
numInput.parentNode.insertBefore(newDiv, numInput.nextSibling);
}
}
<input type="number" id="numInput" name="numInput" onchange="myFunc()">
+Edit
You can also manipulate <form> with javascript.
function myFunc() {
let numInput = document.getElementById("numInput");
while (numInput.nextSibling) {
numInput.nextSibling.remove();
}
let numInputval = document.getElementById('numInput').value;
for(var i=numInputval; i>0; i--) {
var newInput = document.createElement('input');
newInput.setAttribute('id', 'demoInput' + i);
newInput.setAttribute('type', 'text');
newInput.setAttribute('name', 'demoInputName' + i);
newInput.setAttribute('onchange', 'myFormChangeListener(this)');
numInput.parentNode.insertBefore(newInput, numInput.nextSibling);
numInput.parentNode.insertBefore(document.createElement('br'), numInput.nextSibling);
}
}
function myFormChangeListener(element) {
console.log(element);
console.log(element.value);
myForm.action = 'http://the.url/';
myForm.method = 'post';
console.log(myForm);
//myForm.submit;
}
<form id="myForm">
<input type="number" id="numInput" name="numInput" onchange="myFunc()">
</form>

connect conditional statement to form javascript

I've just started learning javascript. I'm trying to create a condition that will turn some text red or blue depending on a number entered into a form, but it's not working and I can't figure out why. Every time the text turns blue no matter what number is entered. It should turn red if the number entered is less than 50. This is what I have:
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var input = document.getElementById("input");
var submit = document.getElementById("submit");
submit.onclick = function() {
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>
You need the value of the input element.
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var submit = document.getElementById("submit");
submit.onclick = function(event) {
// getting the value after click of the button
var input = document.getElementById("input").value;
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>
document.getElementById("input") gets the actual element. You want the value of that element, so use document.getElementById("input").value. You also want to check the value on every click, so you need to move that line within your click handler:
var form = document.querySelector("form");
form.addEventListener("submit", function(event) {
event.preventDefault();
});
var submit = document.getElementById("submit");
submit.onclick = function() {
var input = parseInt( document.getElementById("input").value, 10 );
if (input >= 50) {
document.getElementById("color").style.color = "red";
} else {
document.getElementById("color").style.color = "blue";
};
}
<h3 id="color">Conditional Example</h3>
<form name="form">
<input type="text" id="input"><br>
<button type="submit" id="submit">Submit</button>
</form>

How correctly check if input is not equal zero

I have simple code, in input user inputs number and it must print the numbers until the input is not equal to zero.
And the problem is when i submit value, page stops responding
Here is how my code looks like:
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
while(input !== 0) {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
The value property of input is a string.
You must compare with the correct type:
while (input !== '0')
or
while (input != 0)
----- edit -----
Consider changing the while to an if, otherwise it will print any number different of 0 indefinitely.
window.onload = function() {
var btn = document.getElementsByClassName('btn')[0];
function printInput() {
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if(input !== '0') {
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input+'<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="text" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>
You need to make two changes
Change type attribute from text to number
Change from while to if
Demo
window.onload = function()
{
var btn = document.getElementsByClassName('btn')[0];
function printInput()
{
var output = document.getElementsByClassName('output')[0];
var input = document.getElementsByClassName('input')[0].value;
if (input !== 0)
{
var input = document.getElementsByClassName('input')[0].value;
output.innerHTML += input + '<br>';
}
}
btn.addEventListener('click', printInput);
}
<input type="number" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>

How to clear all dynamically created SPAN elements

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>

Count on click button1 and recount if on click button2

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

Categories

Resources