Increasing and decreasing value of the clicks of the button - javascript

Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.
I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:
var clicks = 0;
function clickME() {
clicks += 1;
if (clicks == 2) {
clicks = 0;
}
document.getElementById("clicks").innerHTML = clicks;
}
<input type="Button" id="bt" />

Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:
function clickME(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
}
Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.
Note:
Don't forget to pass the event data object with the onclick attribute in HTML:
<input onclick="clickME(event)" ...>
Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/

You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset.

On your html:
lets say you have 50 of these
<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
and on your javascript
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
if (this.dataset.clicked == 'false') {
this.dataset.clicked = 'true';
this.innerHTML = parseInt(this.innerHTML) + 1;
}
else {
this.dataset.clicked = 'false'
this.innerHTML = parseInt(this.innerHTML) - 1;
}
})
});
EDIT: Here is a working fiddle

Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same
It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.
$(document).ready(function() {
$(".btn").on("click", clickME);
});
function clickME() {
var clicks = $(this).data("clicks");
var newClicks = parseInt(clicks) + 1;
if(newClicks > 1){
newClicks = 0;
}
// set the new click count on the element
$(this).data("clicks", newClicks);
setTotal();
}
function setTotal(){
var total = 0;
$(".btn").each(function(imdex, btn) {
var currClicks = parseInt($(btn).data("clicks"));
total += currClicks;
});
$("#clicks").text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>

Related

How add attribute to radio element on new items?

The code can add attribute checked="checked" on first item already loaded from HTML markup. But, when I added a new "item" radio element, the code cannot include the attribute checked="checked". Why this happens?
I tested using the browser console (F12) to see if attribute would be included or not on respective radio input clicked, but no success so far.
If I not add checked="checked" my value is not stored on sql table. But if I add checked="checked" manually, editing on my browser console, my value is updated with success on sql table.
How can I fix this situation?
jsfiddle
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
$("[name='s_radio']").on("click", function() {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
});
Let me clarify few things here so you actually learn something:
you are writing the JS code for something HTML radio buttons do them self's. If you put same name attribute in your case name="s_radio" on them they will automatically uncheck others and just live check on the only clicked one, they just need to have same name, and you already did that. This is called grouping inputs:
Example:
var i = 1 ;
var scntDiv = $('#p_scents');
function add_track() {
if(i < 30){
i++;
$('<p><span class="custom_radio"><input type="radio" id="featured-'+ i +'" name="s_radio" value="'+ i +'"> <label for="featured-'+ i +'">item '+ i +'</label></span></p>').appendTo(scntDiv);
}
}
function remove_track() {
if(i > 1){
var select = document.getElementById('p_scents');
select.removeChild(select.lastChild);
i--;
}
}
document.getElementById('add').addEventListener('click', add_track, false);
document.getElementById('remove').addEventListener('click', remove_track, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="p_scents">
<p>
<span class="custom_radio">
<input type="radio" id="featured-1" name="s_radio" value="1"> <label for="featured-1">item 1</label>
</span>
</p>
</div>
<span id="add" class="btn btn-sm btn-primary">add</span>
<span id="remove" class="btn btn-sm btn-pub">remove</span>
So your JS code is complicity unnecessary as HTML will do this for you alone... And it was clearly stated in comments.
You are adding your JS click event listener on page load and it creates a list of elements on page load. You are adding more of them with button and they will not be included in that list. So solution is to bound listener on document itself and when clicked it will check for all elements with added selector.
So do not use $("[name='s_radio']").on("click", function() { where you target just already loaded [name='s_radio'] radios
Use $("document").on("click", "[name='s_radio']", function() { where you will bind document and on click it will check for all [name='s_radio'], new or old. By new I talk about dynamically added with button.
So people do not have problems with radio buttons, Id say radios have problem with some people. And browser IS your friend. You just need to learn to use it.
This should solve the problem
$(document).on('click',"[name='s_radio']",function (e) {
$("[name='s_radio']").attr("checked", false);
$(this).attr("checked", true);
})

Adding css to the button where with the given value in jquery

I have multiple buttons on my page with css qtyButton:
I want to add the css to only button where value matches with the given value. I have used the following code but it is giving me error undefined in the alert box when i try to select the button value.
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>
$(document).on('click','.arrow',function(e){
var curr_qty=$('#qty').val();
var text = $('.qtyButton').filter(function () {
return this.value== curr_qty}).css('color', 'blue');
});
The issue is with this.value - the button doesn't have a .value - your HTML implies that you want to check the .text() of the button (or use this.innerText for more efficiency):
$("#clickme").click(function(e) {
var curr_qty = $('#qty').val();
$('.qtyButton').filter(function() {
return $(this).text() == curr_qty
}).css('color', 'red'); // changed to red as blue wasn't clear enough
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='qty' value="1" />
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>
<hr/>
<button id='clickme'>click me</button>
You need to use .innerText instead .value
return this.innerText == curr_qty
Assuming you have, somewhere in your DOM, a <button> with the class arrow, and a number <input> with the ID qty.
I want to respect your return this.value== curr_qty line, so I added value attributes to your .qtyButton elements.
<button class="arrow" type="button">.arrow</button>
<input type="number" id="qty" value="1">
<br />
<button class="qtyButton" value="1" >1</button>
<button class="qtyButton" value="2" >2</button>
<button class="qtyButton" value="3" >3</button>
$(document).on('click','.arrow',function(e) {
$('.qtyButton').css('color', '');
var curr_qty = $('#qty').val();
var text = $('.qtyButton').filter(function () {
return this.value == curr_qty;
}).css('color', 'blue');
});
I added a color reset of all elements before your logic.
$(document).on('click', function(e) {
var curr_qty = 2
$('.qtyButton').each(function() {
if (parseInt($(this).text()) === curr_qty) $(this).css('color', 'blue')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>

Javascript - Increment Number in Form

I am just trying to increment a number in a form. This works but the input is big, tried to size with no luck. And I don't want the increment up/down inside the input box. Changing the box to text, gets me the right sizing and no up/down. But the increment doesn't work.
Is there an easier way. Also when I put inside a <form> tag, the plus minus button don't work.
function HaFunction() {
document.getElementById("HNumber").stepUp();
}
function HmFunction() {
document.getElementById("HNumber").stepDown();
}
Number: <input type="number" id="HNumber" class=verd15 value="0">
<span class=verd13>
<button onclick="HaFunction()"><b>+</b></button>
<button onclick="HmFunction()"><b>-</b></button>
</span>
You can make the input smaller with CSS:
<input style="width:40px" type="number" id="HNumber" class=verd15 value="0">
Hope this helped
You can write your own function that increments the number in a text input.
If you have a form, make sure your buttons use type="button". By default it's type="submit", so clicking on the button will submit the form and you'll reload the page.
function addToInput(element, amount) {
var val = parseInt(element.value, 10) || 0;
val += amount;
element.value = val;
}
function HaFunction() {
addToInput(document.getElementById("HNumber"), 1);
}
function HmFunction() {
addToInput(document.getElementById("HNumber"), -1);
}
<form>
Number: <input type="text" id="HNumber" class=verd15 value="0">
<span class=verd13>
<button type="button" onclick="HaFunction()"><b>+</b></button>
<button type="button" onclick="HmFunction()"><b>-</b></button>
</span>
</form>

Breadcrumb menu update on button click?

Currently, this is all I have in terms of code for this:
1 >
This <a> link will probably need some changes, since ideally the user could click on the number and revert to that question number.
and 2 buttons
<input class="btn btn-success NavigationButtons" id="BackButton" type="submit" name="Previous" value="Back" />
<input class="btn btn-success NavigationButtons" id="ForwardButton" type="submit" name="NextPage" value="#Session["ForwardButtonText"]" onclick="RadBtnValidation()"/>
So what I need, is every time the user clicks the button with id="ForwardButton" is for the 1 > to change to 1 > 2 > and vice versa whe the user clicks the back button. Thanks in advance
You can store numbers and append they inside a every button click.
var numberList = [];
init();
function init(){
numberList.push(1);
ShowNumber();
}
$("#BackButton").click(function(){
numberList.pop();
ShowNumber();
});
$("#ForwardButton").click(function(){
numberList.push(numberList[numberList.length-1] + 1);
ShowNumber();
});
function ShowNumber(){
$("#txtPageNumber").html("");
for(var i=0; i<numberList.length;i++)
{
$("#txtPageNumber").append(numberList[i] + ">");
}
}
https://jsfiddle.net/gnne36nw/1/

check inputfields on pageload and manipulate with jquery

When I press ADD, I show the hidden #box, I hide the ADD button and show the REMOVE button.
html:
<input type="button" id="add" value="ADD">
<input type="button" class="no-display" id="remove" value="REMOVE">
<div class="no-display" id="box">
<input id="a" value="" type="text" />
<input id="b" value="" type="text" />
<input id="c" value="" type="text" />
</div>
jquery:
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
see working DEMO
Now, I want to check if the input fields #a or #b or #c have a value. If they have a value, on pageload I want to show #box, hide the #add button and show the #remove button.
What is the best way to do this?
you can see a DEMO here (not finished)
using filter() to get the count of the input that has value on it... if count is greater that 0 ..means atleast one input is not empty so.. hide add, show remove buttons and the container
try this
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
var count = $('#a,#b,#c').filter(function () {
return $(this).val().length > 0;
}).length;
if (count > 0) {
$('#box').show();
$('#add').hide();
$('#remove').show();
}
updated as per comment
var count = $('#a,#b,#c').filter(function () {
return this.value.length > 0; //faster
}).length;
working fiddle
Try this: Move toggle code to a function. Bind it to the click. Call it on load if any of the inputs have a value.
$(function () {
var toggleBox = function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
};
$('#add,#remove').click(toggleBox);
if(!!$("#a, #b, #c").filter(function() {return this.value;}).length) {
toggleBox();
}
});

Categories

Resources