How do I add up values of buttons in jquery - javascript

I'm trying to sum up values of buttons if the buttons are clicked on. For example, there is "Button1". If this button is clicked, it should add its value to a sum which will be displayed at the bottom of the page. If "Button1" is clicked a second time it should substract its value from the sum.
Here is my attempt to do this but it's not doing anything at all:
var value_Buttons = 0;
var total = 0;
$("button[name=Button1],[name=Button2],[name=Button3],[name=Button4],[name=Button5],[name=Button6]").click(function() {
if($(this).hasClass('active') == false) {
value_Buttons += parseInt($(this).val());
} else if($(this).hasClass('active') == true) {
value_Buttons -= parseInt($(this).val());
}
total += value_Buttons;
alert(total);
});
total = value_Buttons + value_Optional_Button;
$("input[name=value_sum]").val(total);
Additionally, here is the code for an examplary button (Like "Button1"):
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button1" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">Button 1</button>
</div>
There will be more buttons, but they will only differ in their name and value.
Also, the box which will display the sum of the button-values currently looks like this:
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>
I've searched all over Stackoverflow, as well as via Google, etc. yet I can't find anything or anyone with a similar problem

Blocking JS logic error is here :
$("input[name=value_sum]").val(total);
this line should be in the above code block. Added corrections for substraction :
var total = 0;
$("button[name]").on("click", function() {
if(!$(this).hasClass('active')) {
total += Number($(this).val());
$(this).addClass('active').html("remove " + $(this).attr("title"));
} else {
total -= Number($(this).val());
$(this).removeClass('active').html("add " + $(this).attr("title"));
}
$("input[name=value_sum]").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-md-2">
<button type="button" class="form-control btn btn-primary" name="Button300" value="300" title="300 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 300 €</button>
<button type="button" class="form-control btn btn-primary" name="Button600" value="600" title="600 €" data-toggle="button" aria-pressed="false" autocomplete="off">add 600 €</button>
</div>
<div>
<label class="control-label">Sum</label>
<div class="input-group">
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>
<span class="input-group-addon">€</span>
</div>
</div>

Lines 14 and 15 need to be placed within the click event of the button to update the value_sum input on every click. Also your selection for the value attribute it a little bit off. The way to return the value attribute of a button using jQuery is:
$(this).attr('value');
So after these two points, stripping your code of the if and else check, and also selecting the buttons with a cleaner method, you should have something like this:
var total = 0;
$("button[name=Button1], button[name=Button2], button[name=Button3], button[name=Button4], button[name=Button5], button[name=Button6]").click(function() {
total += $(this).attr('value');
$("input[name=value_sum]").val(total);
});
To display the total, that is 0, in the input element on page load, you could use:
<input class="form-control" name="value_sum" style="text-align:right" id="costs" value="0" type="text" readonly>

start off by create a listener for a class that will be applied to all of your buttons.
$(.btn).click(function() {
//get value
var value = parseint($(this).attr("value"));
//check if already clicked
if($(this).hasClass('active') {
//set value of total
total = total - value;
//remove class active
$(this).removeClass('active');
}else {
//set value of total
total = total + value;
//addclass active
$(this).addClass('active');
}
)};
Is this what you need?

Working Demo
Here have added a classname 'add' for all buttons , on click its toggle class add, sub in you case you using active,inactive class
var total = 0;
$("button[name=button1],[name=button2],[name=button3]").on('click', function () {
var self = $(this);
var gValue = Number(self.val());
if (self.hasClass("add")) {
total += gValue;
self.removeClass("add").addClass("sub");
} else {
total -= gValue;
self.removeClass("sub").addClass("add");
}
$("#costs").val(total);
});

Check this fiddle.
Add as many buttons as you like, the only thing is that you'll have to add a data-value to them to figure out how much to add or substract. I would also do the search for buttons using a class instead of "button" but that's up to you.
var buttons = {};
$("button").each(function (index, item) {
buttons[index] = 0;
$(item).click(function () {
var value = +($(item).data("value")),
val = +($("#costs").val());
val += (!buttons[index]) ? value : -value;
buttons[index] = (!buttons[index]) ? 1: 0;
$("#costs").val(val);
});
});
Hope it helps.

Related

Change only one element after clicking other

I have the following problem:
I would like to change the value of an input field, which is next to an another element, which will be clicked.
HTML:
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
JS:
$(document).on('click', ".plus", function (event) {
let currentTarget = event.currentTarget;
let idOfClickedElement = $(currentTarget).attr('id');
let currentQuantity = Number($('.quantity' + idOfClickedElement).val());
$(this).parent().find(".quantity" + idOfClickedElement).val(currentQuantity + 1)
});
There are other input fields which are the same like in the example. Those value changes also, but I want only one.
As each input with +/- is inside a div wrapper, you can use
$(this).closest("div").find(".quantityNum--input")
to get the related input.
There's no need for the numeric IDs when using relative DOM traversal.
Combining the + and - into a single event gives:
$(document).on('click', ".minus,.plus", function() {
var delta = $(this).is(".plus") ? 1 : -1;
$(this).closest("div").find(".quantityNum--input").val((i, val) => {
console.log(val);
return (val * 1) + delta;
});
});
.minus,
.plus {
cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="100">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="500">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
I thik you are looking for .next and .prev.
note: I like sharing information usingdata-attributes so I've used that. you can use anything else id/class to differentiate. that's upto you
Just created a demo script for you
$('.number-action-button').on('click', function(){
const direction = $(this).data('direction');
if(direction === 'decrement'){
const $input = $(this).next('input[type="number"]');
$input.val($input.val() - 1);
}
if(direction === 'increment'){
const $input = $(this).prev('input[type="number"]');
$input.val(parseInt($input.val()) + 1);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="number-action-button" data-direction="decrement">-</button>
<input type="number" value="0" />
<button class="number-action-button" data-direction="increment" >+</button>
simple solution: bundle the 3 elemts into 1 container, so your parent selector can easily catch the input, the way you already do it.
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
if you cant(or dont want) change the html use $(this).next() (or $(this).prev() for the plus button) in order to fint the input.
btw: maybe you'll try that funktion (havn't tested it, but at least it should give you an idea how to)
$(document).on('click', ".plus,.minus", function (event) {
let input_quantity=false;
if($(this).hasClass('plus'){
input_quantity=$(this).prev();
input_quantity.val(parseInt(input_quantity.val())+1);
}else{
input_quantity=$(this).next();
input_quantity.val(parseInt(input_quantity.val())-1);
}
});

Can't see updated HTML input value from Javascript [duplicate]

This question already has answers here:
Difference between Element.value and Element.getAttribute("value")
(2 answers)
Closed 3 years ago.
If I click the "Show Value" button, it copies the text field value 0.75 to a result label.
But if I change the text field value to something else and click "Show Value", I still get 0.75.
Why is it that the input element's value attribute doesn't change based on the value of the input box?
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: "+edit.getAttribute("value")+" (click #"+n+")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>
(It's not just Javascript; if I look at the page in Chrome and open an Inspect window, the element's value never changes from 0.75.)
It's actually updating the value property of the DOM element and not the value attribute. To make it works use value property of the DOM element.
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: " + edit.value + " (click #" + n + ")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>
You want to use edit.value not edit.getAttribute('value').
edit.getAttribute('value') is getting the attribute value and not the current value since modifying the input doesn't actually update the default attribute's value.
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById('theform');
var edit = form.querySelector("input.parameter");
var btn = form.querySelector("input.showit");
var result = document.getElementById("result");
var n = 0;
btn.addEventListener("click", function(event) {
++n;
result.textContent = "Result: "+edit.value+" (click #"+n+")";
});
});
<div class="container">
<form id="theform">
<label for="R">R</label>
<input type="number" class="parameter" name="R" value="0.75">
<input type="button" class="showit" value="Show Value">
<label id="result">Result: </label>
</form>
</div>

How To Add two Textbox values with jquery and also add two more textboxs that are apend from the same textboxs

enter image description herethis is simple text boxes i give the value and add them ![enter image description here][2]
when I add more text boxes with append query now the sum is not calculating
[enter image description here][3]
THis is jquery code of iam apending two divs with Two ids and text boxes are also have there ids
Use jquery features for implement complex thing in a very easier way...
It provides Huge Library with number of functions and Flexibility for executing your code in cross browsers
HTML
<div class="row">
<button type="button" class="btn btn-success add-more">ADD MORE</button>
</div>
<div class="form-group" id="ele">
<div class="row" id="item1">
<div class="row">
<input type="number" class="num1">
<label>+</label>
<input type="number" class="num2">
<label>SUM</label>
<input type="number" class="sum" readonly="true">
<button type="button" class="btn btn-success remove">x</button>
</div>
</div>
</div>
JQUERY Script
var item = $('#item1').html();
var cnt = 0;
$('.add-more').click(function() {
cnt++;
$('#ele').append("<div class='row' id='item" + cnt + "'>" + item + "</div>");
});
$(document).on('click', '.remove', function() {
$(this).closest('.row').remove();
});
$(document).on('keyup', '.num1,.num2', function() {
if ($(this).hasClass('num1')) {
var num1 = parseInt($(this).val());
var num2 = parseInt($(this).siblings('.num2').val());
$(this).siblings('.sum').val(num1 + num2);
} else if ($(this).hasClass('num2')) {
var num2 = parseInt($(this).val());
var num1 = parseInt($(this).siblings('.num1').val());
$(this).siblings('.sum').val(num1 + num2);
}
});
Check Demo Here

Calculating TOTAL in added input fields

I have this small problem. I have been checking out the net to find an answer, but it is mostly for input fields which aren't generated / added.
<script>
$(document).ready(function(){
/* --- ADD FIELD --- */
$('.TotalMultiField').each(function() {
var $wrapper = $('.multiFields', this);
$(".addField", $(this)).click(function(e) {
$('.multiField:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
/* --- REMOVE FIELD --- */
$('.multiField .removeField', $wrapper).click(function() {
if ($('.multiField', $wrapper).length > 1)
$(this).parent('.multiField').remove();
});
});
</script>
Above is the Jquery script to add and remove fields. And below is the HTML code. As you see, in the "insert a number" field, the total should appear in the span id="added".
<form role="form" action=""" method="">
<div class="TotalMultiField">
<div class="multiFields">
<div class="multiField">
<input type="date">
<input type="number" class="number" placeholder="Insert a number">
<button type="button" class="removeField">Remove</button>
</div>
</div>
<button type="button" class="addField">Add field</button>
</div>
Total:<span id="added"></span>
</form>
Just noticed you updated that you do indeed want a sum, here is a fiddle with the total calculated on blur and when you remove a row, bind additional events as required (some tidy up is required, but this should get you started):
http://jsfiddle.net/1ggaco1d/4/
The below code does the totaling:
function total() {
var total = 0;
$(".number").each(function (idx, el) {
var value = $(el).val();
if (value !== "") {
total = total + parseFloat($(el).val());
}
});
$("#added").text(total);
}
Please check the below fiddle
https://jsfiddle.net/srsu4rne/
You should be able to just count the classes in the div
var multiField = $('.multiField').length
$('#added').html(multiField);

jQuery add ID increment to .html() appending on input onchange and refresh onchange value

I apologize for the wordy title but I haven't found a solution to my problem yet. I am a newbie with jQuery and web development so any guidance would be appreciated.
I have a <input> that allows user to enter a value (number) of how many rows of a set of input fields they want populated. Here's my example:
<div id="form">
<input id="num" name="num" type="text" />
</div>
<p> </p>
<div id="form2">
<form action="" method="post" class="form_main">
<div class="data">
<div class="item">
<input id="name" name="name[]" type="text" placeholder="name" /><br/>
<input id="age" name="age[]" type="text" placeholder="age" /><br/>
<input id="city" name="city[]" type="text" placeholder="city" /><br/>
<hr />
</div>
</div>
<button type="submit" name="submit">Submit</button>
</form>
My jQuery:
<script>
var itemNum = 1;
$("#num").on("change", function() {
var count = this.value;
var item = $(".item").parent().html();
//item.attr('id', 'item' + itemNum);
for(var i = 2; i <= count; i++) {
itemNum++;
$(".data").append(item);
}
})
</script>
I'm having problems adding an ID item+itemNum increment to <div class="item">... item.attr() didn't work. It doesn't append once I added that line of code.
Also, how can I get it so that once a user enters a number that populates rows of input fields, that if they change that number it will populate that exact number instead of adding to the already populated rows? Sorry if this doesn't make any sense. Please help!
Here is a DEMO
var itemNum = 1;
$("#num").on("change", function() {
$('.data div').slice(1).remove(); //code for removing previously populated elements.
var count = this.value;
console.log(count);
var item;
//item.attr('id', 'item' + itemNum);
var i;
for(i = 1; i <= count; i++) {
console.log(i);
item = $("#item0").clone().attr('id','item'+itemNum);
//prevent duplicated ID's
item.children('input[name="name[]"]').attr('id','name'+itemNum);
item.children('input[name="age[]"]').attr('id','age'+itemNum);
item.children('input[name="city[]"]').attr('id','city'+itemNum);
itemNum++;
$(".data").append(item);
}
})
Use clone() instead of html()
Try
var itemNum = 1,
item = $(".data .item").parent().html();;
$("#num").on("change", function () {
var count = +this.value;
if (itemNum < count) {
while (itemNum < count) {
itemNum++;
$(item).attr('id', 'item' + itemNum).appendTo('.data')
}
} else {
itemNum = count < 1 ? 1 : count;
$('.data .item').slice(itemNum).remove();
}
})
Demo: Fiddle

Categories