Keep button from decrementing a number after 1st use with Javascript - javascript

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;
}
};

Related

How can I create a button that increments a counter when clicked?

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>

Onclick the jquery event button color not changing

I have three buttons, Button 1 & Button 2 & Button 3. My requirement is that if Button 2 is clicked, the background color should change using an onclick event. I have tried but I am not able to do this. If I click Button 2, button 1 color is changing. If I click Button 3 , Button 1 color is changing.
var count = 1;
function setColor(btn, color) {
var btn = 'button';
var color = '#101010';
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" id="button" onclick="setColor()">Button 1</button>
<button type="button" id="button" onclick="setColor()">Button 2</button>
<button type="button" id="button" onclick="setColor()">Button 3</button>
My Updated code
$.ajax({
type: "POST",
data: {city:city,locality:locality},
url: "rentlocalityFilter.php",
success:function(data){
var htmlString='';
$.each( res['data'], function( key, value ) {
var id = value.id;
htmlString +='<a class="col-md-1 icon" style="margin-top:10px;cursor:pointer" onclick="guesttt_login()"><i class="fa fa-heart" aria-hidden="true" style="margin-top: -11px; color: red;" id="button" id="button" onclick="setColor('+value.id+')"></i></a>';
});
}
});
var count = 1;
function setColor() {
var btn = 'button';
var color = '#101010';
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}
Id's on a Html-page have to be unique.
what you need to do is give ID's like:
<button type="button" id="button1" onclick="setColor('button1')">Button 1</button>
<button type="button" id="button2" onclick="setColor('button2')">Button 2</button>
<button type="button" id="button3" onclick="setColor('button3')">Button 3</button>
and change your javascript-Code:
var count = 1;
function setColor(_btn, color) {
var btn = _btn;
var color = '#101010';
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "red"
count = 0;
}
}
Try this,
<button onclick="setColor(this)">Button 1</button>
<button onclick="setColor(this)">Button 2</button>
<button onclick="setColor(this)">Button 3</button>
var count = 1;
function setColor(btn) {
var color = '#101010';
// doesn't need getElementById anymore, use btn directly because we gave 'this'
if (count == 0) {
btn.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
btn.style.backgroundColor = "red"
count = 0;
}
}
jsfiddle
Edit 1:
Your last update make sense but still not enough to make a solution because we still don't know about value, I can just say that you should also give Id like this, id="'+value.id+'" onclick="setColor('+value.id+') or you can remove this line and use jquery
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
var count = 1;
$(document).ready(function() {
$("button").click(function() {
var btn = $(this);
var color = '#101010';
if (count == 0) {
btn.css("backgroundColor", "#FFFFFF");
count = 1;
} else {
btn.css("backgroundColor", "red");
count = 0;
}
});
});
jquery solution
Hope helps,
Look this example, is working and have less code.
Just pass the element clicked to the function and with toggleClass you can change the background color.
http://api.jquery.com/toggleclass/
function setColor(elem) {
$(elem).toggleClass('active')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button type="button" id="button1" onclick="setColor(this)">Button 1</button>
<button type="button" id="button2" onclick="setColor(this)">Button 2</button>
<button type="button" id="button3" onclick="setColor(this)">Button 3</button>
<style>.active{background-color:red}</style>
You can simply do it like this
var count = 1;
function setColor(btn) {
var color = '#101010';
var butn = document.getElementById(btn);
if (count == 0) {
butn.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
butn.style.backgroundColor = "red"
count = 0;
}
}
You also need to pass value.id with in id attribute
htmlString +='<a class="col-md-1 icon" style="margin-top:10px;cursor:pointer"> <i class="fa fa-heart" aria-hidden="true" style="margin-top: -11px; color: #8bc34a;" id="'+value.id+'" onclick="setColor('+value.id+')"></i></a>'
Html code like this:
<button type="button" id="button1" onclick="setColor('button1')">Button 1</button>
<button type="button" id="button2" onclick="setColor('button2')">Button 2</button>
<button type="button" id="button3" onclick="setColor('button3')">Button 3</button>
JavaScript code like this:
var count = 1;
function setColor(btnId) {
var color = '#101010';
if (count == 0) {
btnId.style.backgroundColor = "#FFFFFF";
count = 1;
}
else {
btnId.style.backgroundColor = "red";
count = 0;
}
}
I hope help you.

How to change button color onClick if I have multiple buttons

If I have a single button , it is possible to change color this way ,,
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
But how to do this if I have multiple buttons and multiple colors (eg: 10 buttons with 3 possible colors )
var count = 1;
function setColor(btn, color) {
var btns = document.getElementByClass("button_class_name");
for(var i = 0; i < btns.length; i++) {
btns.item(i).style.backgroundColor = "#7FFF00"
}
}
This will set all the buttons with the class "button_class_name" to "7FFF00".
Try like this.Toggle with three color's for all Button's .Create the color array .Then count the num of click's with data-count of the each button element .Then Match the count with color array using this.dataset.count%col.length
var count = 1;
document.querySelectorAll('button').forEach(function(a){
a.addEventListener('click', setColor)
})
var col = ["#FFFFFF","#AAAAAA","#6A76A7"];
function setColor() {
this.dataset.count= this.dataset.count >= 0 ? ++this.dataset.count : 0;
this.style.backgroundColor = col[this.dataset.count%col.length]
}
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
<button>one</button><br>
Maybe you're looking for something like that.
HMTL
<button class="buttons" id="btn-1">Button1</button>
<button class="buttons" id="btn-2">Button2</button>
<button class="buttons" id="btn-3">Button3</button>
<button class="buttons" id="btn-4">Button4</button>
<button class="buttons" id="btn-5">Button5</button>
CSS
.buttons {
border: none;
background: transparent;
padding: 10px 20px;
}
JS
// Change one button color
function setButtonColor(btn, color) {
btn.css({'background': color});
}
// Change a set of buttons color
function setButtonsColor(btns, colors) {
$.each(btns, function (key, value) {
setButtonColor($(value), colors);
});
}
$(function(){
setButtonsColor( $('.buttons'), 'gold')
setButtonColor( $('#btn-1'), 'red' );
setButtonColor( $('#btn-3'), 'purple' );
$('.buttons').click(function(){
setButtonColor( $(this), 'lightgreen' );
});
});
Suppose you have ten buttons , give a common class to all buttons .Bind events to each one of them as below.
var classname = document.getElementsByClassName("btns");
var count =1;
var setColor = function() {
var button = this;
if (count == 0) {
button.style.backgroundColor = this.getAttribute("data-color");
console.log(this.getAttribute("data-color"))
count = 1;
}
else {
button.style.backgroundColor = this.getAttribute("data-color");
console.log(this.getAttribute("data-color"))
count = 0;
}
};
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', setColor, false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btn1" data-color="#7FFF00" value="btn1" class="btns">
<input type="button" id="btn2" data-color="#7FFF00" value="btn2" class="btns">
<input type="button" id="btn3" data-color="#FC0" value="btn3" class="btns">
<input type="button" id="btn4" data-color="#FFFPPP" value="btn4" class="btns">
<input type="button" id="btn5" data-color="#FC0" value="btn5" class="btns">
<input type="button" id="btn6" data-color="#7FFF00" value="btn6" class="btns">
<input type="button" id="btn7" data-color="#7FFF00" value="btn7" class="btns">
<input type="button" id="btn8" data-color="#FC0" value="btn8" class="btns">
<input type="button" id="btn9" data-color="#FFFPPP" value="btn9" class="btns">
<input type="button" id="btn10" data-color="#FC0" value="btn10" class="btns">
If you want to give each one of them have to be different color , you can put data attributes to buttons data-color='#FC0' for example and assign this color as dynamically.
If you have ES6 support you can replace your last line with:
Array.from(classname).forEach(function(element) {
element.addEventListener('click', setColor);
});
Using an object based approach. Makes for easy to extend functionality at a later date.
My understanding of the questions is each of the buttons will cycle through each of the colours depending on how many times the button has been clicked.
For example, 1 click = red, 2 clicks = green...
// Only 3 colours and buttons for a test.
// This list of colours
var cList = ['#f00','#0f0','#00f'];
// The butExtend object will become an array here
var butList = [];
// This object keeps track of the number of button clicks.
var ButExtend = function butObj(id) {
this.count = 0;
if (document.getElementById(id)) {
document.getElementById(id).addEventListener('click',bClick,false);
}
};
// Called on a button click
function bClick() {
this.style.backgroundColor = cList[butList[this.id].count];
butList[this.id].count++;
if (butList[this.id].count >= cList.length) {
butList[this.id].count = 0;
}
}
window.onload = function() {
// The list of id's for the buttons.
var bId = ['b1','b2','b3'];
for(x in bId) {
butList[bId[x]] = new ButExtend(bId[x]);
}
}
<button id="b1">but 1</button>
<button id="b2">but 2</button>
<button id="b3">but 3</button>

JS NaN after array[index]

I just started programming with js again and having some trouble.
This is the code i have problems with:
var actual = [10,50,20];
var sum = 0;
for(var i = actual.length; i > 0; i--){
sum = sum + actual[i];
}
What did i do wrong?
Start loop from actual.length-1, because every array starts from 0, so last element is actual.length-1 not actual.length.
I see Your calculator code is too complicated.
You do low level operation to add just "1" You multiply all things to 10 and add 1.
Be simple (;
var inputElement = document.getElementById("input");
var resultElement = document.getElementById("result");
var accept = [0,1,2,3,4,5,6,7,8,9,'-','+','calc'];
var input = [];
function op(value){
if(accept.indexOf(value) < 0) {
return;
}
if(value == 'calc') {
return calc();
}
input.push(value);
inputElement.innerHTML = input.join('');
}
function calc() {
resultElement.innerHTML = eval(input.join(''));
input = [];
}
<button onclick="op(1)">1</button>
<button onclick="op(2)">2</button>
<button onclick="op(3)">3</button>
<br/>
<button onclick="op(4)">4</button>
<button onclick="op(5)">5</button>
<button onclick="op(6)">6</button>
<br/>
<button onclick="op(7)">7</button>
<button onclick="op(8)">8</button>
<button onclick="op(9)">9</button>
<br/>
<button onclick="op(0)">0</button>
<button onclick="op('.')">.</button>
<button onclick="op('calc')">=</button>
<hr/>
<button onclick="op('+')">+</button>
<button onclick="op('-')">-</button>
<hr/>
INPUT:<div id="input"></div>
DISPLAY:<div id="result"></div>

How to implement onclick event only for current button?

I want to show/hide div with children on button click, but not other same divs in different parent blocks.
Sorry for my bad explanation and js knowledge, maybe the code can speak better:
for (a = 0; a < document.querySelectorAll("#hidereplies").length; a++) {
var btn = document.querySelectorAll("#hidereplies")[a];
btn.onclick = function () {
for (var y = 0; y < document.querySelectorAll(".reply_comments").length; y++) {
var reply = document.querySelectorAll(".reply_comments")[y];
reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
}
};
}
Demo on jsfiddle.
There's a few things you're doing wrong.
First, in your HTML, don't use an ID more than once. You've given your buttons the same ID.
Next, assign your querySelector results to an array and iterate the array.
Third, you need to scope your query. You're checking for elements on the document so everything gets pulled in rather than being scoped to the current div.
//note that I've changed from an ID to a class for your buttons
var buttons = document.querySelectorAll(".hidereplies");
for (a = 0; a < buttons.length; a++) {
var btn = buttons[a];
btn.onclick = function (event) {
var btn = event.currentTarget; //get the current button clicked
var comments = btn.parentNode.querySelectorAll(".reply_comments"); //scope the search
for (var y = 0; y < comments.length; y++) {
var reply = comments[y];
reply.style.display = (reply.style.display != 'none' ? 'none' : 'block');
}
};
}
HTML
<div class="comments_list">
<div class="comment_item">
<div class="comment_body">test1 - comments</div>
<input type="button" class="hidereplies" value="show replies" />
<div class="reply_comments">
<div class="comment_body">want to hide only current ".reply_comments"</div>
</div>
</div>
<div class="comment_item">
<div class="comment_body">test2 - comments</div>
<input type="button" class="hidereplies" value="show replies" />
<div class="reply_comments">
<div class="comment_body">but not all</div>
</div>
</div>
<div class="comment_item">
<div class="comment_body">test3 - no comments</div>
<div class="reply_comments"></div>
</div>
</div>
Your updated fiddle - http://jsfiddle.net/yhtKa/4/

Categories