I am trying to make a button that increments a counter's value by 1 when clicked. My code, however, doesn't seem to work.
var count = 1;
var button = document.querySelector("#increment");
button.addEventListener("click", function() {
var increment = document.getElementById("#count");
increment.value = count;
count++;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button id="decrement">Decrement</button>
<button id="increment">Increment</button>
</div>
You don't need # in getElementById and use innerHTML to set value.
Don't use querySelector when you can get by id.
Like this:
let count = 0;
const button = document.getElementById("increment");
const button2 = document.getElementById("decrement");
const textHolder = document.getElementById("count");
textHolder.innerHTML = count;
button.addEventListener("click", function() {
textHolder.innerHTML = ++count;
});
button2.addEventListener("click", function() {
textHolder.innerHTML = --count;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button id="decrement">Decrement</button>
<button id="increment">Increment</button>
</div>
Your code have some issues
Use # in query selector, remove it, it use in jquery
Wrong attribule value change to innerText
Change querySelector to getElementById to get id
var count = 1;
var button = document.getElementById("increment");
button.addEventListener("click", function() {
var increment = document.getElementById("count");
increment.innerText = count;
count++;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button id="decrement">Decrement</button>
<button id="increment">Increment</button>
</div>
.document.getElementById() doesn't need CSS selector indicator, you can just pass the id value directly here is how to do it, note that I'm using + operator to make sure that the textContent parsed into integer, and to increment the value you can just add ++ after that to count tag that we have reference to, here is a working snippet:
var count = 1;
var IncrementBtn = document.querySelector("#increment");
var decrementBtn = document.querySelector("#decrement");
IncrementBtn.addEventListener("click", function() {
var increment = document.getElementById("count");
+increment.textContent++;
});
decrementBtn.addEventListener("click", function() {
var decrement = document.getElementById("count");
+decrement.textContent--;
});
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button id="decrement">Decrement</button>
<button id="increment">Increment</button>
</div>
You can do this with this short JS inserted in the HTML button elements:
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button onclick="document.getElementById('count').innerText--">Decrement</button>
<button onclick="document.getElementById('count').innerText++">Increment</button>
</div>
If you want to use a function you can try something like this:
function changeValue(diff) {
var count = document.getElementById('count');
count.innerText = +count.innerText + diff;
}
<h4>Current count: <span id="count">0</span></h4>
<div class="container">
<button onclick="changeValue(-1)">Decrement</button>
<button onclick="changeValue(1)">Increment</button>
</div>
Related
I am creating a Todo app and I need to trigger a function (which counts number of checkboxes checked) when any one of the checkboxes is checked.
I am unable to get an onlick event to happen if a checkbox is clicked. I have manage to do it with a submit button, but not with the checkbox itself
//the html
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<button class="button center" onClick="newTodo()">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
</div>
// the function above this one creates the checkbox and appends it to the list in the HTML
const box = document.createElement('INPUT');
box.type = "checkbox";
box.name = "countme";
box.id = "checkme"
li.appendChild(box);
// this is the code I have created to trigger a function unchecked which returns the count of unchecked checkboxes.
let getcheck = document.getElementsByName("countme");
for (let i = 0; i < getcheck.length; i++) {
getcheck[i].onClick = unchecked;
}
Nothing is happening so I am unsure with how to debug this
i think you need this
function newTodo() {
let ulElement = document.getElementById('todo-list');
let todoElement = document.createElement('li');
const box = document.createElement('INPUT');
box.type = "checkbox";
box.name = "countme";
box.id = "checkme";
box.value = 0;
todoElement.appendChild(box);
const span = document.createElement('span').TEXT_NODE = 'To do task';
todoElement.append(span);
ulElement.append(todoElement);
let unCheckELement = document.getElementById('unchecked-count');
unCheckELement.textContent = parseInt(unCheckELement.textContent) + 1;
box.onchange = onCheckboxCheck;
}
function onCheckboxCheck(element) {
let count = parseInt(document.getElementById('item-count').textContent);
count += element.srcElement.checked ? 1 : -1;
let allElements = document.querySelectorAll('#todo-list li').length;
document.getElementById('item-count').textContent = count;
document.getElementById('unchecked-count').textContent = allElements - count;
}
<div class="flow-right controls">
<span>Item count: <span id="item-count">0</span></span>
<span>Unchecked count: <span id="unchecked-count">0</span></span>
</div>
<button class="button center" onClick="newTodo()">New TODO</button>
<ul id="todo-list" class="todo-list"></ul>
I have a span tag and a button tag
<span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
I want to append more span tag with new class from this array with increment value by clicking button.
Like this output:
<span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
i try `
this JsFiddle
But i can not add class name to new append tag from array.
Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here
value increaseesenter code here this snippet
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
another attempt...anyone can help.. to get desire output
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;
$("#add").click( function() {
(i < elements.length){
$(".new-field").append('<span class="myspan">1</span><script');
var value = parseInt($(".myspan").text(), 10) + 1;
elements[i].className += ' ' + backgrounds[i%len];
i++;
$(".background").text(i);
}
});
*/
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
<script> var i = 0; function buttonClick() {i++; document.getElementById('inc').value = i; } </script> <button onclick="buttonClick();">Click Me</button> <input type="text" id="inc" value="0"></input>
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt used convert ths string to number
var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var len = backgrounds.length;
$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
$(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
})
console.log($(".new-field").html())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>
<button id="add">Add +1</button>
<div class="new-field">
</div>
Check the fiddle. Hope this helps!
HTML :
<div id="mainContainer">
<span class="myspan">1</span>
</div>
<button id="add">Add +1</button>
JS :
var arr = ["myspan1", "myspan2", "myspan3", "myspan4"];
$("#add").on("click", function() {
var spans = $("span");
var classList = [];
$.each(spans, function() {
var elemCls = $(this).attr('class').length > 1 ? $(this).attr('class').split(' ') : $(this).attr('class');
if (elemCls) {
$.each(elemCls, function() {
classList.push(this.toString());
});
}
});
$.each(arr, function(i, e) {
if ($.inArray(e, classList) == -1) {
$("#mainContainer").append("<span class='" + e + "'>" + parseInt(spans.length + 1) + "</span>");
return false;
}
});
});
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
function randomQuote () {
var array = [1,20,50,100];
}
document.getElementById("btn").onclick = randomQuote;
document.getElementById("par").innerHTML = array[0];//then on another btn click array[1]...
for(var i=0; i<array.length;i++){
quote[i];
}
On "btn" click number 1 from array is shown in "par" paragraph
on another btn click number 2 shows up and 1 dissapear, and so on...
Use counter cpt as index to loop through the array and show the values :
var array = [1,20,50,100];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
function randomQuote ()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
Minified version could be :
function randomQuote ()
{
document.querySelector("#par").innerHTML = array[cpt<array.length-1?++cpt:cpt=0];
}
Snippet using Random color as you comment say :
var array = ["Quotes 1","Quotes 2","Quotes 3","Quotes 4"];
var cpt = 0;
//Init the 'par' div before click
document.querySelector("#par").innerHTML = array[cpt];
//Init Random Color before click
getRandomColor();
function randomQuote()
{
if(cpt<array.length-1)
cpt++;
else
cpt=0;
document.querySelector("#par").innerHTML = array[cpt];
}
function getRandomColor()
{
document.querySelector("#par").style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
}
<div id="wrapper">
<p id="par"></p>
<button id="btn" onClick="randomQuote();getRandomColor()">Next quote</button>
</div>
Is this what you want?
var counter = 0;
function randomQuote () {
var array = [1,20,50,100];
document.getElementById("par").innerHTML(array[counter++]);
}
save the index, increment it on each click and then reset it when its undefined.
var index = -1;
function randomQuote() {
var array = [1, 20, 50, 100];
document.getElementById('par').innerText = (array[++index] || array[index=0]);
}
<div id="wrapper">
<div class="quotes">
<p id="par"></p>
</div>
<button class="btn" onClick="randomQuote()">button</button>
</div>
I have a counter in javascript right now and a button that adds 1 value to the counter, this is what I have so far:
var counter = 0;
var a = 0;
var add = function(valueToAdd){
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
I need a button to reset the counter back to 0 any help is appreciated.
Add a button, reset function and set values to "0" as shown in code below:
<button width="500" height="500" id ="reset" class="button button1"
onclick="javascript:reset()">Reset Value</button>
<script type="text/javascript">
var reset= function(){
a = 0;
document.getElementById('Value').innerHTML = a;
}
</script>
BTW you declared var count = 0 in your code (question) but not using that (apparently).
Some tips:
You correctly stored a variable to keep track of the counter, all you needed to do in a reset function was to change the value back to 0.
Keep your Javascript away from your HTML. Here's a good article
Your code should be properly formatted when posting on Stack Overflow.
Here's a cleaner solution:
HTML:
Value $<span id="Value">0</span>
<button id="add">Add Value</button>
<button id="reset">Reset</button>
Javascript:
var a = 0;
var add = function(valueToAdd) {
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
var reset = function() {
a = 0;
document.getElementById('Value').innerHTML = 0;
}
var addButton = document.querySelector("#add");
var resetButton = document.querySelector("#reset");
addButton.addEventListener("click", function() {
add(1);
})
resetButton.addEventListener("click", function() {
reset();
})
JSFiddle: https://jsfiddle.net/sfh51odm/
Do not define a out of function as a general variable. Every time set the current value to a and continue. So you can get back to zero:
var counter = 0;
var add = function(valueToAdd){
var a = parseInt(document.getElementById('Value').innerHTML);
a += valueToAdd;
document.getElementById('Value').innerHTML = a;
}
function reset(){
document.getElementById('Value').innerHTML=0;
}
Value $<span id="Value">0</span>
<button width="500" height="500" id = add class="button button1" onclick="javascript:add(1)">Add Value</button>
<button width="500" height="500" id = add class="button button1" onclick="javascript:reset()">Reset</button>
var a = 0;
var displayValue = document.getElementById('Value');
var updateValue = function () {
displayValue.innerHTML = a;
};
var add = function (valueToAdd) {
a += valueToAdd;
updateValue();
};
var reset = function () {
a = 0;
updateValue();
};
Value $<span id="Value">0</span>
<button onclick="add(1)">Add 1</button>
<button onclick="reset()">Reset</button>
if you need to do a page refresh (like if you press F5 on the keyboard) this will work for you.
the "location.reload();" will work also.
change '.again' to a btn name you want.
document.querySelector('.again').addEventListener('click', function () { location.reload(); });
I'm trying to keep track of the number of items a user has clicked on by removing one from the counter span using a basic JS function. I have to keep track of anywhere between 5 to 10 items so each time the button is clicked I am removing one from the div span that keeps count. It's working but I do not want it going to negative values. How do I keep the button from removing 1 after it has been used once? Basically, I want the function to only fire once for each button.
Here is the codepen as it is now:
CODEPEN
Here is what I have right now:
var currentValue = 9;
var add = function(valueToAdd){
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;
if (this.currentValue == 0) {
alert("YOU ARE AT 0 ");
currentValue - 0
}
if (!isNaN(currentValue) && currentValue > 0) {
// Decrement one
currentValue - 1;
} else {
return false;
}
};
HTML:
<div id="text">Number of items:<span id="number">9</span><div>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
You have great interest in inserting the buttons programmatically, you'll have a much greater flexibility. And you can hook the function to a function that you bind to have the right this .
Below is the code for buttons that handle a 'quantity' property, and disable themselves when quantity reaches 0.
http://codepen.io/anon/pen/gJtry
<div id="text">Number of items:<span id="number">9</span>
<div id="oneTimeButtons">
</div>
<div id='youDidIt' hidden>!!! You did it !!!</div>
code :
var buttonCount = 9;
var quantityPerButton = 1; // try 2 or more
var totalValue = 0;
var gID=document.getElementById.bind(document);
var elem = gID('oneTimeButtons');
for (var i=0; i<buttonCount; i++) {
var bt = document.createElement('button');
bt.id='qttBt'+i;
bt.onclick = add.bind(bt, -1);
bt.quantity=quantityPerButton;
totalValue+=bt.quantity;
bt.buildTitle = function( i) {
this.innerHTML='Qtty button '+i+' ('+this.quantity+')';
}.bind(bt, i);
bt.buildTitle();
elem.appendChild(bt);
}
gID('number').innerHTML=totalValue;
function add (valueToAdd) {
this.quantity+=valueToAdd;
this.buildTitle();
if (this.quantity ==0) this.disabled=true;
totalValue += valueToAdd;
gID('number').innerHTML = totalValue;
if (totalValue == 0) {
console.log("YOU ARE AT 0 ");
gID('youDidIt').hidden=false;
}
};