Add multiple input values and assign it to a variable - javascript

I need to add multiple input text values and assign it to a variable. i can add it now and send it to an id but i want to get it out as a variable. Please see below for the variable's condition after the js code
My HTML
<input type="text" name="quant[1]" class="form-control input-number" value="0" min="0" max="5">
<input type="text" name="quant[2]" class="form-control input-number" value="0" min="0" max="5">
<input type="text" name="quant[3]" class="form-control input-number" value="0" min="0" max="5">
<input type="text" name="quant[4]" class="form-control input-number" value="0" min="0" max="5">
0
The JS
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".input-number").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".input-number").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
The above code adds up and sets the value to the id sum, i want the addition to not hapn when the first 2 values already gives an output of 5. the max value shd be 5 so the input fields should be like 2,1,1,1 or 2,3,0,0 or 5,0,0,0 summation value shd be 5 if it is achieved in the first input field itself then the summation should not continue.

Try this (push values to an array as an example or if you want string just concatenate the values):
var variable = [];
self.forEachValue = function(key, element){
variable.push(element.value);
};
$(".input-number").map(self.forEachValue);
console.log(variable);

Related

Multiply input values

Inputs are invisible to jQuery when they are appended.
THere are 3 inputs
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
with this code
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});
If I have these inputs in my html created manually, I can multiply the inputs value and add the result into the total price input.
But I need these inputs to appear after the click event, so I append them. After that they become invisible to jQuery, hence nothing works.
How can I make these inputs appear on the page, in the form, and then manipulate their values?
You did only one mistake while assigning the value to the input field which displays the multiplication result
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
let tot=value * $price.val();
$(".bul-order-info__total").val(tot);
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
</body>
</html>
Jquery can't find dynamically generated elements directly.
You can access them using it's parent which is not appended dynamically.
$(document).on('change', "body .bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});

jquery increment input values

Using Jquery I need to add all values of input.
Using jquery each is there any way to use regix in element name
like
items[regix_goes_here][debit]
I need values of all input and I want them incremented using each.
My code
<input name="items[1][debit]" type="number">
<input name="items[341][debit]" type="number">
<input name="items[31][debit]" type="number">
<input name="items[431][debit]" type="number">
First, assign a class to your inputs, for example:
<input class="js-inc" name="items[1][debit]" type="number">
<input class="js-inc" name="items[341][debit]" type="number">
<input class="js-inc" name="items[31][debit]" type="number">
<input class="js-inc" name="items[431][debit]" type="number">
Now you can increment all of them, without even jquery. Use .value to access the value as a string. Use Number("..") to convert it to a number. Add one to it, and assign it back.
var inputs = document.querySelectorAll("input.js-inc")
inputs.forEach(function(input) {
input.value = Number(input.value) + 1
})
Here's a live example
If you want to sum all the values of inputs with name="items[X][Y]", you can filter them by testing if their name attribute matches this /items\[\d+\]\[debit\]/ Regex.
This is how should be your code:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
Demo:
var sum = 0;
$('input[type="button"]').click(function() {
$('input').each(function() {
if ($(this).attr('name') && $(this).attr('name').match(/items\[\d+\]\[debit\]/)) {
sum += $(this).val() ? parseInt($(this).val()) : 0;
}
});
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="items[1][debit]" type="number" value="2">
<input name="items[341][debit]" type="number" value="2">
<input name="items[31][debit]" type="number" value="2">
<input name="items[431][debit]" type="number" value="2">
<input type="button" value="SUM" />

<span id="sample">0</span> to new input box

I recently have a result in a modal from calculatesum JavaScript displayed as <span id="sample">0</span> (the value will increase based on the number key in by users)
How do I display this final sample value in another input box outside of the modal? Help?
JavaScript as below:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(0));
}
HTML or rangeslide code as below:
<input type="text" class="form-control slider-text-field" id="homeContentInput" placeholder="250,000">
</td><td> (RM)</td></tr></table>
<br/>
<input type="range" value="250000" min="15000" max="500000" step="10000" id="homeContentRange">
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max">RM 500,000</span>
Basically, I need to replace placeholder="250,000" for the first input box and value="250000" with the final value from <span id="sample">0</span>.
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
//$("#sum").html(sum.toFixed(0));
$("#homeContentInput").val(sum.toFixed(0));
$("#homeContentRange").val(sum.toFixed(0));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
*****************************************************************
<br>if you just want to add up the values then this will work, else you need to be more clear with your question.
<br>form2-1:
<input class="txt" type="text" id="form2-1" value="0">
<br>form2-2:
<input class="txt" type="text" id="form2-2" value="0">
<br>form2-3:
<input class="txt" type="text" id="form2-3" value="0">
<br>Not sure what you want to do bellow this... *****************************************************************
<br>
<input type="text" class="form-control slider-text-field" id="homeContentInput" placeholder="250,000">(RM)
<br>
<input type="range" value="250000" min="15000" max="500000" step="10000" id="homeContentRange">
<br>
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max ">RM 500,000</span>
<br>*****************************************************************
Not sure if I understand this right but I think you want something along these lines?
I assume you want
the first field readonly
the second field as the slider
on submit calculates the total, in which you can post the results in another div.. In your case a modal.
Place the result where ever you like
<p id="result"> </p>
<input id="value1" type="text" value="250000" readonly="readonly"/>
<span> + </span>
<input id="value2" type="text" id="textInput" value="15000">
<span class="slider-label-min">RM 15,000</span> <span class="slider-label-max">RM 500,000</span>
<input type="submit" onclick="output();">
<p id="result"> </p>
<input type="range" type="range" value="250000" min="15000" max="500000" step="10000" onchange="updateTextInput(this.value);">
<script type="text/javascript" language="javascript" charset="utf-8">
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
document.getElementById('result').innerHTML = parseInt(value1) + parseInt(value2);
}
function updateTextInput(val) {
document.getElementById('value2').value=val;
}
</script>

in multiple input field enter the different numbers how can add automatically in javascript

in multiple input field enter the different numbers how can add automatically in javascript
how can i find sum of different input field in different numbers in javascript.
"the input field is n numbers..:" and this input fields i using the clone function
only consider in numbers field not related for text field
almost this model
note:but my condition is here is different name and id
how can i do ?
pleas help me..
You can have onchange event on all inputs that are needed to be summed
<input class="sum" onchange="add()" />
and can add and place the sum into the the total input like below
function add(){
total= 0;
sum =document.getElementsByClassName("sum");
for(a=0;a<sum.length;a++)
{
console.log(sum[a].value);
total += parseInt(sum[a].value || 0);
}
document.getElementById("total").value = total;
}
Code/Demo:
function add(){
total= 0;
sum =document.getElementsByClassName("sum");
for(a=0;a<sum.length;a++)
{
console.log(sum[a].value);
total += parseInt(sum[a].value || 0);
}
document.getElementById("total").value = total;
}
One <input class="sum" onchange="add()" /><br/>
Two <input class="sum" onchange="add()" /><br/>
Three <input class="sum" onchange="add()" /><br/>
Four <input class="sum" onchange="add()" /><br/>
Total <input id="total" /><br/>

jQuery: How to add float values in multiple fields using class name

Using jQuery, I have float values in fields with similar class names "score"and I just want to make a function that will add all float values in those fields and assign the result to "field5".
<input id="field1" type="text" class="score">2.5</input>
<input id="field2" type="text" class="score">6.02</input>
<input id="field3" type="text" class="score">1</input>
<input id="field4" type="text" class="score">4.03</input>
<input id="result" type="text" class="result"></input>
I made the script below but it doesn't work even though the function executes.
$(.score).on('change',function(){
var total = 0
$(this).each(function(){
total += this.value;
});
});
$('#result').val(total);
});
Lot of issues in your code:
JS:
$(".score").on('keyup', function () {
var total = 0
$(".score").each(function () {
total += parseFloat(this.value);
});
$('#result').val(total);
});
HTML
<input id="field1" type="text" class="score" value="1"/>
<input id="field2" type="text" class="score" value="1.2"/>
<input id="field3" type="text" class="score" value="1.4"/>
<input id="field4" type="text" class="score" value="3.1"/>
<input id="result" type="text" class="result" value=""/>
Demo: http://jsfiddle.net/GCu2D/839/
input is a self closing tag. You should use it like in this example
You should iterate on $(".score") instead of $(this) to get all input values. Latter will give only the current input's value.
Use parseFloat to convert the string type into float. By default you get string value from the .value. In order to add them, you need to convert them to float
Your selector $(.score) is invalid. Use $(".score") .
$('#result').val(total); should be inside the event handler.
First of all, I believe .change() is used with dropdowns. Try using .keydown() to detect a change in an input box.
There are a few errors in your code -
var total = 0;
Semicolon is missing.
$('#result').val(total);
This will assign the value and will not show it. If you wish to display teh value as well, use
$('#result').append(total);
$(document).ready(function(){
$(".score").on('change',function(){
var total = 0.00;
$(".score").each(function(){
if(undefined != $(this).val() && "" != $.trim($(this).val()))
total += parseFloat($(this).val());
});
$('#result').val(total);
});
});
I finally figured it out. Thanks guys!
function getResult(){
var total = 0;
$('.score').each(function(){
var checkval= parseFloat(this.value);
if(!isNaN(checkval)) total += checkval;
});
$('#result').val(total.toFixed(2));
}

Categories