I want to have multiple plus/minus counters on my page.
I have one working counter but want to make it generic so that multiple counters can have a different initial value and increase and decrease as clicked.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('.output').html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
<hr />
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>
Fiddle Link:
http://jsfiddle.net/u2Lh7dbp/
Thanks
Each output element should be unique so it can be called by itself.
$('.counter-btn').click(function(e) {
e.preventDefault();
var $btn = $(this);
$('#output-' + $btn.data('index')).html(function(i, val) {
val = val * 1 + $btn.data('inc');
return (val <= 0 ? '' : '+') + val;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-index="1" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-index="1" data-inc="-1">-</button>
<div class="output" id="output-1">+30</div>
<hr />
<button class="counter-btn" id="increase2" type="button" data-index="2" data-inc="1">+</button>
<button class="counter-btn" id="decrease2" type="button" data-index="2" data-inc="-1">-</button>
<div class="output" id="output-2">+30</div>
I've added a new data attribute: index. You can use that index to specify the exact output element you're looking for by its id.
Keeping it simple, you can have two functions and directly associate the onClick callback to these functions, making it more clear on the html side.
function add(id) {
var newCount = parseInt($(id).text()) + 1;
$(id).text(newCount);
}
function substract(id) {
var newCount = parseInt($(id).text()) - 1;
$(id).text(newCount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="add('#output1')">+</button>
<button type="button" onclick="substract('#output1')">-</button>
<div id="output1">30</div>
<hr />
<button type="button" onclick="add('#output2')">+</button>
<button type="button" onclick="substract('#output2')">-</button>
<div id="output2">30</div>
Related
I have 10 different buttons each have a common class and a unique class.
<button type="button" class="topic btn1" data-target="desc1">Safety</button>
<button type="button" class="topic btn2" data-target="desc2">Environment</button>
<button type="button" class="topic btn3" data-target="desc3">Climate change</button>
<button type="button" class="topic btn4" data-target="desc4">Sustainability</button>
<button type="button" class="topic btn5" data-target="desc5">Business strategy</button>
<button type="button" class="topic btn6" data-target="desc6">Performance data</button>
<button type="button" class="topic btn7" data-target="desc7">Working for Shell</button>
<button type="button" class="topic btn8" data-target="desc8">Working together</button>
<button type="button" class="topic btn9" data-target="desc9">Social performance</button>
<button type="button" class="topic btn10" data-target="desc10">Human rights</button>
A function is applied on that which will add one extra unique class to each button.
for (let i = 0; i <= 12; i++) {
$( ".btn" + i ).click(function() {
$( this ).toggleClass( "act-btn" + i );
});
}
Now i want to create two buttons:-
Show All: When some one click on this, third unique class act-btn1 to act-btn10 will be added in the same order.
Reset: When someone click on that reset button, only the extra added class will be removed, rest will be same.
$('.add').click(function() {
for (let i = 1; i <= 10; i++) {
$('.btn' + i).addClass( "act-btn" + i);
}
});
$('.remove').click(function() {
for (let i = 1; i <= 10; i++) {
$('.btn' + i).removeClass( "act-btn" + i);
}
});
<button class="add">Add class</button>
<button class="remove">remove class</button>
I have multiple buttons on my page. I want to get the values for those and displayed in one line. How do I do that.
I have 3 buttons, onclick they return these values:
Dark : returns 'scoop'
Danger : returns 'swoosh'
Warning : returns 'spoon'
I have one big button (info), on clicking that I want that to return: scoop&swoosh&spoon
How do I do that?
let val;
$('#one').on('click', function(){
val = 'scoop';
});
$('#two').on('click', function(){
val = 'swoosh';
});
$('#three').on('click', function(){
val = 'spoon';
});
$('#main').on('click', function(){
console.log(val);
//Expected value: scoop&swoosh&spoon
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<div><button id="one" type="button" class="btn btn-dark m-3">Dark</button></div>
<div><button id="two" type="button" class="btn btn-danger m-3">Danger</button></div>
<div><button id="three" type="button" class="btn btn-warning m-3">Warning</button></div>
<hr />
<div><button id="main" type="button" class="btn btn-info btn-block">Info</button></div>
Currently, each click resets the variable, assigning a new value. Consider using an Array and updating it with a new item for each click.
Example:
let val = [];
$('button').on('click', function() {
switch ($(this).attr("id")) {
case "one":
val.push('scoop');
break;
case "two":
val.push('scoop');
break;
case "three":
val.push('scoop');
break;
}
});
$('#main').on('click', function() {
console.log(val.join(" & "));
// Example Value: scoop & swoosh & spoon
// Clear the array
val = [];
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<div><button id="one" type="button" class="btn btn-dark m-3">Dark</button></div>
<div><button id="two" type="button" class="btn btn-danger m-3">Danger</button></div>
<div><button id="three" type="button" class="btn btn-warning m-3">Warning</button></div>
<hr />
<div><button id="main" type="button" class="btn btn-info btn-block">Info</button></div>
New To JQuery, i have the following code which i think is a bit over kill as all i'm trying to do i match a returned value to a selection of buttons and add/remove a class.
HTML for days of the week buttons
<div class="form-horizontal" id="selectWeekdaysSection">
<div class="form-group">
<div class="col-md-offset-2 col-lg-4">
<button id="mon" name="weekdaysbutton" class="btn btn-default" type="button" value="Mon">Mon</button>
<button id="tue" name="weekdaysbutton" class="btn btn-default" type="button" value="Tue">Tue</button>
<button id="wed" name="weekdaysbutton" class="btn btn-default" type="button" value="Wed">Wed</button>
<button id="thur" name="weekdaysbutton" class="btn btn-default" type="button" value="Thur">Thur</button>
<button id="fri" name="weekdaysbutton" class="btn btn-default" type="button" value="Fri">Fri</button>
<button id="sat" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sat">Sat</button>
<button id="sun" name="weekenddaysbutton" class="btn btn-default" type="button" value="Sun">Sun</button>
</div>
</div>
</div>
Gives this on the site
DataTable data
When i do call and get data back from my DataTable it pre-selects the days from the JSON. I have all this working but as i said seems over kill to have to keep repeating the IF just for a different button especially when i have to do this for days '01 - 31'
Jquery
var selectedDays = modifyRecordData.selectedDays;
var splitSelectedDays = selectedDays.split(',');
splitSelectedDays.forEach(day => {
let val = day.trim();
if(val == 'Mon') {
$('#mon').removeClass('btn-default');
$('#mon').addClass('btn-primary');
}
if (val == 'Tue') {
$('#tue').removeClass('btn-default');
$('#tue').addClass('btn-primary');
}
if (val == 'Wed') {
$('#wed').removeClass('btn-default');
$('#wed').addClass('btn-primary');
}
if (val == 'Thur') {
$('#thur').removeClass('btn-default');
$('#thur').addClass('btn-primary');
}
if (val == 'Fri') {
$('#fri').removeClass('btn-default');
$('#fri').addClass('btn-primary');
}
if (val == 'Sat') {
$('#sat').removeClass('btn-default');
$('#sat').addClass('btn-primary');
}
if (val == 'Sun') {
$('#sun').removeClass('btn-default');
$('#sun').addClass('btn-primary');
}
})
Console.Log of returned data
The technique you want to follow is called Don't Repeat Yourself, or DRY for short.
In this case the day is always the same as the id of the element you want to target, so you can manually build the selector string once from that. You can also use toggleClass() instead of alternate addClass() and removeClass() calls. Try this:
splitSelectedDays.forEach(day => {
let dayName = day.trim().toLowerCase();
$('#' + dayName).toggleClass('btn-default btn-primary');
})
The clear() function in this code is not running when I press the "C" button (i.e. it isn't even printing to console) even though all the other buttons work fine. I'm sure I've missed something obvious but I cannot see it. Please help me find it:
<html>
<head>
<script type="text/javascript">
var total = 0;
function add(x) {
total += x;
document.getElementById('total').innerHTML = total;
}
function clear() {
console.log('cleared');
var total = 0;
document.getElementById('total').innerHTML = 0;
}
</script>
</head>
<body>
<p id="total">0</p>
<p>
<button type="button" onclick="add(1)">1</button>
<button type="button" onclick="add(2)">2</button>
<button type="button" onclick="add(3)">3</button><br>
<button type="button" onclick="add(4)">4</button>
<button type="button" onclick="add(5)">5</button>
<button type="button" onclick="add(6)">6</button><br>
<button type="button" onclick="add(7)">7</button>
<button type="button" onclick="add(8)">8</button>
<button type="button" onclick="add(9)">9</button><br>
<button type="button" onclick="clear()">C</button>
</p>
</body>
</html>
window.document.clear is Native API hence function clear() is shadowed, Use some other function name.
<html>
<head>
<script type="text/javascript">
var total = 0;
function add(x) {
total += x;
document.getElementById('total').innerHTML = total;
}
function clearVal() {
console.log('cleared');
total = 0;
document.getElementById('total').innerHTML = 0;
}
</script>
</head>
<body>
<p id="total">0</p>
<p>
<button type="button" onclick="add(1)">1</button>
<button type="button" onclick="add(2)">2</button>
<button type="button" onclick="add(3)">3</button><br>
<button type="button" onclick="add(4)">4</button>
<button type="button" onclick="add(5)">5</button>
<button type="button" onclick="add(6)">6</button><br>
<button type="button" onclick="add(7)">7</button>
<button type="button" onclick="add(8)">8</button>
<button type="button" onclick="add(9)">9</button><br>
<button type="button" onclick="clearVal()">C</button>
</p>
</body>
</html>
Note: You are initializing variable total in clearVal function, not redefining it as 0, remove keyword var to update global variable.
Not suggested but hacked way to do it and freaking cooool:
window.document.clear is Native API hence function clear() is shadowed
But if you still want to keep the clear function name, you can also
override the window.document.clear a function like shown below.
<html>
<head>
<script type="text/javascript">
var total = 0;
function add(x) {
total += x;
document.getElementById('total').innerHTML = total;
}
window.document.clear = function() {
console.log('cleared');
total = 0;
document.getElementById('total').innerHTML = 0;
};
</script>
</head>
<body>
<p id="total">0</p>
<p>
<button type="button" onclick="add(1)">1</button>
<button type="button" onclick="add(2)">2</button>
<button type="button" onclick="add(3)">3</button><br>
<button type="button" onclick="add(4)">4</button>
<button type="button" onclick="add(5)">5</button>
<button type="button" onclick="add(6)">6</button><br>
<button type="button" onclick="add(7)">7</button>
<button type="button" onclick="add(8)">8</button>
<button type="button" onclick="add(9)">9</button><br>
<button type="button" onclick="clear()">C</button>
</p>
</body>
</html>
I want to be able to increment and also decrement a value (5) and I would like to cover this with one function (I know how to do it with two).
Unfortunately I am not able to get it done and can't figure out what is wrong.
Here is my code:
HTML:
<form>
<button type="button" value="minus" onclick="updateAmount();">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount();">
+
</button>
</form>
JS:
var num = parseInt(document.getElementById('number');
var btn = document.querySelector('button');
btn.addEventListener('click', updateAmount);
function updateAmount(){
btn.value === "minus" ? num-- : num++;
document.getElementById('number').value = num;
}
Also at JSfiddle
I would prefer a vanilla JS solution if possible, but any suggestion is welcome :)
Thanks!
The minimal-changes to your approach is to pass an argument to the function:
function updateAmount(value) {
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(-1);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(1);">
+
</button>
</form>
Or use your value attribute and pass this into the function:
function updateAmount(btn) {
var value = btn.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
That latter approach combines nicely with modern event handling:
// Scoping function so our `updateAmount` isn't global
(function() {
document.querySelector("button[value=minus]").addEventListener("click", updateAmount);
document.querySelector("button[value=plus]").addEventListener("click", updateAmount);
function updateAmount() {
var value = this.value == "minus" ? -1 : 1;
console.log("Update it by: " + value);
}
})();
<form>
<button type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus">
+
</button>
</form>
You could hand over the action as a parameter
<form>
<button type="button" value="minus" onclick="updateAmount('minus');">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount('plus');">
+
</button>
</form>
and then
function updateAmount(action) {
var num = parseInt(document.getElementById("number").innerHTML, 10);
switch(action) {
case 'minus':
num--;
break;
case 'plus':
num++;
break;
}
document.getElementById("number").innerHTML = num;
}
You can try this ...
<html>
<form>
<button type="button" value="minus" onclick="updateAmount(this.value);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this.value);">
+
</button>
</form>
<script>
function updateAmount(value){
var num = parseInt(document.getElementById('number').innerHTML);
value=='plus'?num++:num--;
document.getElementById('number').innerHTML = num;
}
</script>
</html>
You were close, as you have multiple elements use document.querySelectorAll() with valid selector to get there reference and bind event handlers.
As you are using <SPAN> element, it doesn't have value property, need to use textContent property.
var btns = document.querySelectorAll('button');
btns.forEach(function(btn) {
btn.addEventListener('click', updateAmount);
});
function updateAmount() {
var num = parseInt(document.getElementById('number').textContent.trim(), 10);
this.value === "minus" ? num-- : num++;
document.getElementById('number').textContent = num;
}
<button type="button" value="minus">-</button>
<span id="number">5</span>
<button type="button" value="plus">+</button>
Note: Get rid of ugly inline click handlers.
simply use like this updateAmount(this)
function updateAmount(that) {
var number = document.getElementById('number');
var num = parseInt(number.innerHTML);
num = (that.value == "minus") ? --num : ++num;
number.innerHTML = num;
}
<form>
<button type="button" value="minus" onclick="updateAmount(this);">
-
</button>
<span id="number">
5
</span>
<button type="button" value="plus" onclick="updateAmount(this);">
+
</button>
</form>
var minusBtn = document.querySelector('#minus');
var plusBtn = document.querySelector('#plus');
minusBtn.addEventListener('click', updateAmount('minus'));
plusBtn.addEventListener('click', updateAmount('plus'));
function updateAmount(action) {
return function() {
var numberElem = document.getElementById('number');
var number = numberElem.innerText;
number = parseInt(number, 10);
if (action === 'minus') {
number--;
} else if(action === 'plus') {
number++;
} else {
throw new Error('invalid operator');
}
numberElem.innerText = number;
};
}
<form>
<button id = "minus" type="button" value="minus">
-
</button>
<span id="number">
5
</span>
<button id = "plus" type="button" value="plus">
+
</button>
</form>
this is a good example for curry function, you can currify your updateAmount to accept action as a part of argument
Your code has just two small flaw, rest is perfect.
Firstly Your variable num is evaluating to NaN.
Secondly you should use textContent instead of value .
I am sharing correct way to evaluate num and then it will work.
var el =document.getElementById('number')
var num = parseInt(el.textContent);
Again, while updating
document.getElementById('number').textContent = num
Hope it helped.