Finding the value of multiple input boxes - javascript

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.

You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">

This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.

Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

Related

Set input value with Javascript on outside click

i want to set a max value to a number input. I used the "max" HTML attribute but the user can write a number over the max value anyway. Is there any way to reset the value of that input to the maximum value I set it, after the user sets it beyond the maximum value? Maybe when the user clicks outside that input?
Here is my code
<input type="number" name="days" id="days" min="1" max="365" value="<?php echo $ipq[0]['valueParam']?>">
You might want to consider using a range control along with the value of the range being shown in a span element next to it. This way only the value range you specify is allowed (which is really what the range control is for).
const output = document.getElementById("output");
document.getElementById("days").addEventListener("input", function(){
output.textContent = this.value;
});
<input type="range" name="days" id="days" min="1" max="365" value="1"><span id="output">1</span>
The max attribute is validated on form submit. AS you can see in the snippet below the user will get a message when he tries to submit the form.
<form>
<input type="number" name="days" id="days" min="1" max="365" value="366">
<input type='submit'>
</form>
If you want to prevent the user for inputting a value over 365 you can use js to do that. The snippet below shows how to prevent values over 365 for all number inputs.
document.querySelectorAll('input[type="number"]').forEach((el) => el.addEventListener('input', (e) => {
let inputEl = e.currentTarget;
if(parseFloat(inputEl.value) > parseFloat(inputEl.max)) {
inputEl.value = inputEl.max;
}
}));
<form>
<input type="number" name="days" id="days" min="1" max="365" value="366">
<input type='submit'>
</form>

Not getting total value of input tags

Why my codes is not getting the total value of each row?, its getting only the first row value.
tried to insert it into .each function, but its not functioning
function calc_total()
{
total=0;
$('#po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
}
get the grand total of each rows.
You need to select your inputs differently so you can add their total. Id's must be unique so it won't let you .each a single element. If you give them each a class with the same name you can do it like this:
var total = 0;
$('.po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="4">
<input type="input" class="po_total_amount" value="90">
<input type="input" id="totalPrice">

Calculate 2 sets of input types using javascript in one html page

I have 2 set of input types of text boxes. 2 fields on each. I am trying to calculate and compare each set individually in single page.
The input types have different ids.
<input type="text" id="tmcp_textfield_1" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_2" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3" name="a3" placeholder="a3" value="0">
<br>second set below<br>
<input type="text" id="tmcp_textfield_3" name="blueberry"
placeholder="blueberry" value="0" onkeydown="calculate()"
onkeyup="calculate()">
<input type="text" id="tmcp_textfield_4" name="plums" placeholder="plums" value="0"
onkeydown="calculate()" onkeyup="calculate()">
<input type="text" id="a3`" name="a3" placeholder="a3" value="0">
My javascript in header:
For First set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_1').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_2').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 6) {
$('#tmcp_textfield_2').val('');
$('#tmcp_textfield_1').val('');
alert('Combination must be below 6');
}
}
</script>
For Second Set:
<script type="text/javascript">
calculate = function() {
var blueb = parseFloat($('#tmcp_textfield_3').val());//document.getElementById('blueberry').value;
var plumsb = parseFloat($('#tmcp_textfield_4').val());//document.getElementById('plums').value;
var thetotal = /*document.getElementById('a3').value =*/ parseInt(blueb)+parseInt(plumsb);
if (thetotal > 12){
$('#tmcp_textfield_4').val('');
$('#tmcp_textfield_3').val('');
alert('Combination must be below 12');
}
}
</script>
The problem only the first set of calculation work. When i remove the first set of javascript then the second set only work and vise versa.
How could i differentiate the sets in javascript so that both the set of inputs work together in one single html page.
Problem:
You are having same name functions "calculate()" for both sets that's why only 1 is working at a time.
Solution:
Rename the function name to different names like calculateOne() and calculateTwo() then both will work.
Hope this helps

How to calculate form fields values to update hidden field value?

I want to know how to calculate the input values of the following fields
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
And update the span text and the hidden field value
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
Thanks in advance
This should do what you want to achieve:
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">
I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!
$("input").on("blur",function(){
var total = 0;
$("[type='text']").each(function(){
if($(this).val() != "") {
total += parseInt($(this).val());
}
});
$("#amountTotal").text(total);
$("#total").val(total);
});
Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event
$('.auto-sum').keyup(function(){
var a=0;
$('.auto-sum').each(function(){
a+=parseFloat($(this).val())
})
$('#amountTotal').text(a|0)
$('#total').val(a|0)
console.log($('#total')[0].outerHTML)//its show the hidden field value
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum" value="2" >
<input type="text" name="score2" class="auto-sum" value="5">
<input type="text" name="score3" class="auto-sum" value="5">
TOTAL <span id="amountTotal" >0 </span>
<input id="total" type="hidden" name="total" value="">
You can use <input type="number" /> inputs to force values entered to be a number.
From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum
Using the each function you can add the numeric to an accumulator to get the total.
You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.
function getTotal() {
var total=0;
$('input.auto-sum').each(function(i,e)
{
total += Number($(e).val());
});
$('#amountTotal').text(total);
$('#total').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Score 1: <input type="number" name="score1" class="auto-sum"><br />
Score 2: <input type="number" name="score2" class="auto-sum"><br />
Score 3: <input type="number" name="score3" class="auto-sum"><br />
TOTAL: <span id="amountTotal">0 </span><br />
<input id="total" type="hidden" name="total" value="">
<input type="button" id="btnTotal" onclick="getTotal()" value="Get Total" />
Please try this one.
$('.auto-sum').on('change',function(){
var totalvalue=0;
$('.auto-sum').each(function(a,b){
totalvalue=totalvalue+parseInt(($(b).val()=='' || isNaN($(b).val()))?0:$(b).val());
});
$('#amountTotal').text(totalvalue);
$('#total').val(totalvalue);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0</span>
<input id="total" type="hidden" name="total" value="">
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
<input type="button" id="calculator" value="Caculate">
$("#calculator").on("click",function (){
var result=0;
var sum_fields=$(".auto-sum");
for(var i=0;i<sum_fields.length;i++){
if(!isNaN(sum_fields[i]) && sum_fields[i]>0){
result += sum_fields[i];
}
}
$("#amountTotal").text(result);
$("#total").val(result);
});
Create array for the fields and loop through them
Check if it not a NaN and more than 0 add them to the result then after the loop attach the result to the hidden field and as a span text
I post this as an answer because the comment areas are to small
At first i think it´s an good idea to write
<input type = "number">
when you don´t want to display the small arrows look at this solution:
https://css-tricks.com/snippets/css/turn-off-number-input-spinners/
the keyup event ist the best way to "live" display the total sum
At last take a look at vue.js
This is the best solution for this scenario.
if you're interested in a pure javascript solution:
All inputs have an oninput event attribute that fires when the input is changed.
You can attach an event handler to the event like so:
<input oninput="updateTotal" />
where updateTotal is a function declared in your script:
function updateTotal { /* code that updates the total */ }
OR if you select the input in your script then you can attach the event handler like this:
selectedInput.oninput = function updateTotal () {
...
}
Here's my implementation that selects all the inputs with the class "auto-sum", assigns the event handler to each of them and updates the code by looping over each input's value attribute:
https://jsfiddle.net/billy_reilly/5dd24v81/2/
function displaySum () {
var sum = 0;
// iterate over the input fields
$('.auto-sum').each(function () {
var value = $(this).val() || 0;
var number = parseInt(value, 10); // parse the input value to an integer
if (isNaN(number)) {
number = 0;
}
sum += number; // add the value to the sum
});
// set the value of the two elements
$('#amountTotal').text(sum);
$('#total').val(sum);
}
// whenever the value of one of the input fields changes, call the displaySum function
$('.auto-sum').on('change, keyup', displaySum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="score1" class="auto-sum">
<input type="text" name="score2" class="auto-sum">
<input type="text" name="score3" class="auto-sum">
TOTAL <span id="amountTotal">0 </span>
<input id="total" type="hidden" name="total" value="">

calculating the sum of the array form with javascript

I want to display the number of values ​​in array form. I have a lot of form with only one name is "price []" and have each value on the form. I want to calculate the total value of the form "price []". I'm still a beginner in javascript. and I want to calculate it by using javascript. The following coding that I have made.
<html>
<body>
<form id="hitung" name="hitung">
price 1 <input type="text" name="price[]" class="price" value="1000"/><br>
price 2 <input type="text" name="price[]" class="price" value="3000"/><br>
price 3 <input type="text" name="price[]" class="price" value="2000"/><br>
price 4 <input type="text" name="price[]" class="price" value="1000"/><br>
price 5 <input type="text" name="price[]" class="price" value="3000"/><br><br>
total <input type="text" name="total" class="total"/>
</form>
</body>
</html>
and I want to ask you again, if there is a new input from the outside, then the total will also be changed directly. how to do it. help me please. thank you
Here's an example: http://jsfiddle.net/c4UyA/1/
var sum = 0;
$("form > input[name='price[]']").each(function() {
$this = $(this);
sum += parseInt($this.attr("value"));
});
$("form > input[name='total']").attr("value", sum);

Categories

Resources