Sum up all text boxes with a particular class name? - javascript

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?

In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>

I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>

Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

Related

Javascript get value of current number input field

I am trying to make a shopping cart. Now i want to update the price of the item when the amount is changed, but when there are more than one items the onchange method only reacts on the first one. They have the same name. I can give them an other name but how will i then get the name of that input field.
I hope someone can help me with this.
Thanks in advance.
function updatePrice() {
var element = this;
console.log(element.value);
}
Your onchange event should iterate over all input fields.
If you give your fields a common identifier (a data-id attribute or a class name), then the process is quite trivial:
document.body.addEventListener("change", ()=> calc());
function calc(){
let items = document.querySelectorAll(".inp");
let total = 0.0;
for (let i = 0; i < items.length; i++) {
total += parseFloat(items[i].value);
}
document.querySelector(".result").value = total.toFixed(2);
}
calc();
<input type="text" class="inp" value="10.00">
<input type="text" class="inp" value="15.00">
<input type="text" class="inp" value="50.99">
<p>Result: <input type="text" class="result" value="00.00"></p>

Javascript - prevent onclick event from being attached to all elements with same class

I'm working on a simple form that includes an input field where the user will fill in the required amount by clicking the incrementor/decrementor. The form is created based on data pulled dynamically from the database
Below is the problematic part: html and the jquery handling it:
The incrementor, decrementor and the input field:
-
<input type="text" id="purchase_quantity" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
and the jquery handling the above:
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(".purchase_quantity").val(num);
return false;
});
});
Now, what's happening is: onclick of the incrementor/decrementor (+ and -) the value on the input field changes across all the fields in the page instead of the one clicked only. Have spent quite some time on this with no success and will appreciate some help
The line
$(".purchase_quantity").val(num);
says, literally, to change the value on all the fields. Earlier you used
$(this).siblings('.purchase_quantity').val()
to get the value, so why not also use
$(this).siblings('.purchase_quantity').val(num)
to set it?
That's because siblings will get you all items on the same level.
Get the siblings of each element in the set of matched elements,
optionally filtered by a selector.
Place them in separate div elements, and adjust your setter to actually only update the siblings inside that div.
jQuery(function ($) {
$('.addItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num++;
if(num>6)num=6;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
$('.removeItem').on('click', function () {
var inputval = $(this).siblings('.purchase_quantity').val();
var num = +inputval;
num--;
if(num<1)num=1;
console.log(num);
$(this).siblings('.purchase_quantity').val(num);
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
-
<input type="text" id="purchase_quantity2" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
<div>
-
<input type="text" id="purchase_quantity1" class = "purchase_quantity" min="1" max="6" delta="0" style = "width: 32px;" value="1">
+
</div>
you should change $(".purchase_quantity").val(num) to $("#purchase_quantity").val(num)

Simple JavaScript function returns function and not value

I'm just starting out and I'm trying to build a simple calculation function that will display the result of 2 numbers on a page. When the submit button is hit the output is the function and not the value. Where have I gone wrong?
HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
You have several issues with your javascript. Let's break them down one by one:
var price = function() {
parseFloat(document.getElementById("price"));
}
document.getElementById returns an element. parseFloat would try to calculate the element, and not the value in this case (Which would always be NaN or Not a Number). You want the value of this element, so using .value will return the value. Furthermore, you're not actually doing anything with the value. (You should use return to return the float found, or set it to another variable.)
var final = function() {
final = price * tax;
final = total
}
price and tax are both functions in this case. You can't simply multiply them to get your desired result. Using var total = price() * tax(); will set the variable total to the float returned from price() and tax() now. Returning this value to the function will fix the next line:
document.getElementById("output").innerHTML = final;
final here is also a function. You want to call it by using final().
Your final script:
var total = function() {
var price = function() {
return parseFloat(document.getElementById("price").value);
}
var tax = function() {
return parseFloat(document.getElementById("tax").value);
}
var final = function() {
var total = price() * tax();
return total
}
document.getElementById("output").innerHTML = final();
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
You have several issues, you put some code into function without calling them.
Another problem is, you need the value of the input tags.
'use strict';
var total = function() {
var price = parseFloat(document.getElementById("price").value);
// get value ^^^^^^
var tax = parseFloat(document.getElementById("tax").value)
// get value ^^^^^^
// calculate directly the final value
var final = price * tax;
document.getElementById("output").innerHTML = final;
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
<div id="output"></div>
Delete
var final = function() {
final = price * tax;
final = total
}
and instead put
return price * tax;

applying onkeyup function simultaneously on multiple textboxes

Suppose I have a column of 1+7 text box. Name of the first box is mm1 and the other boxes are respectively dd1, dd2, ...., dd7. I want to write a javascript function so that all the values in the textboxes dd1, dd2,...,dd7 are multiplied by N if I put N in the first textbox namely mm1. I can write the javascript function , but how to make its effect in all boxes simultaneously? I have tried the following code. But it can effect only one box depending on the value of $i. If we can create a loop for $i taking values 1 to 7, then perhaps the problem will be solved. Any clue please.
<?php $i=3?>
<input type="text" size="1" id="mm1" name="mm1"
maxlength="2" onfocus="this.select()"
onkeyup="gft('dd<?php echo $i?>', 'mm1')"
>
Try this, use class to logically group elements...
$('.mult').each(function(i,v){
var tt = parseFloat($(this).val());
$(this).attr('data-val',$(this).val());
});
$('.myVal').on('keyup',function(e){
var t = $(this).val();
if(!t) t = 0;
$('.mult').each(function(i,v){
if(t>0){
var tt = parseFloat($(this).attr('data-val')) * t;
$(this).val(tt);
}
});
});
Find working fiddle here
function gft(x){
n = 5;
c = x * n;
textInputs[0].value = c;
textInputs[1].value = c;
textInputs[2].value = c;
}
var textInputs = document.querySelectorAll('input[type=text]');
//this eventlistener is made to listen for key movement on all text fields that are of type text
for(i=0;i<textInputs.length;i++){
textInputs[i].addEventListener('keyup',function(){
//gft will execute an equation whenever one of these fields change
//also, it will change all the values inside the textfield simultaneously
gft(this.value);
},false);
}
I made a JSFiddle using only JavaScript (no jQuery):
HTML
<input type="number" onkeyup="multiply(this)"/>
<input type="number" value="1" class="multiply-this"/>
<input type="number" value="2" class="multiply-this"/>
<input type="number" value="3" class="multiply-this"/>
<input type="number" value="4" class="multiply-this"/>
<input type="number" value="5" class="multiply-this"/>
<input type="number" value="6" class="multiply-this"/>
<input type="number" value="7" class="multiply-this"/>
JavaScript
function multiply(first){
var value = +first.value;
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
if(textbox.attributes.initialValue){
textbox.value = textbox.attributes.initialValue.value;
} else {
textbox.setAttribute("initialValue", textbox.value);
}
textbox.value = +textbox.value * value;
}
}
window.onload = function(){
var textboxes = document.getElementsByClassName("multiply-this");
for(var i = 0; i < textboxes.length; i++){
var textbox = textboxes[i];
textbox.onkeyup = function(){
this.setAttribute("initialValue", this.value);
}
}
}
I added functionality to remember what value the textboxes had at first. But you can still change it if you specifically change one of the 7 textboxes that gets multiplied.
EDIT
You can also add this if you want it to multiply after changing one of the values:
textbox.onblur = function(){
multiply(document.getElementById("multiplyer"));
}
JSFiddle

Calculate sum and multiply its value

I'm calculating the sum of a and b and putting it in text box named sum.
After I enter a number in number text box, it should calculate the final = sum * number.
<input type="text" class="txt_1_0" name="a" />
<input type="text" class="txt_1_0" name="b" />
<input type="text" id="sum" name="sum" />
<input type="text" class="number" name="number" />
<input type="text" class="final" name="final" />
I tried the following:
$(document).ready(function() {
$(".txt_1_0").change(function() {
var total = 0.00;
var textbox3 = 0.00; // this gonna be your third textbox
$(".txt_1_0").each(function() {
total += parseFloat(this.value) / 5;
});
textbox3 = $("#sum").val((total).toFixed(2));
});
});
How do I get the number value and calculate final?
You haven't actually added any function that would do the final calculation. So to multiply the sum (subtotal) with number, do the following:
$(".number").change(function () {
var final = $("#sum").val() * $(this).val();
$('.final').val(final);
});
Here is a demo - note that I have removed the division by 5 from your previous function as it didn't make sense from the the way your question was asked.
Or you can use keyup event with this jQuery code Fiddle
<script type="text/javascript">
$(document).ready(function(){
$('input[type="text"]').on('keyup',function(){
var a=parseFloat($('.txt_1_0:first').val())
var b=parseFloat($('.txt_1_0:last').val())
if(a && b){$('#sum').val(a+b)}
var number=$('.number').val()
if(number){
$('.final').val($('#sum').val()*number)
}
})
})
</script>

Categories

Resources