Sum input fields by using javascript [duplicate] - javascript

This question already has answers here:
compute sum dynamically with javascript
(5 answers)
How get total sum from input box values using Javascript?
(9 answers)
Closed 9 years ago.
How could I sum the fields automaticly (by each function) to sum some input fields like this:
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
Thank you very much if anyone has a suggestion?

Use jQuery;
<script src="{path to jquery}/resources/js/vendor/jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function() {
var total = 0;
$.each($('input'), function(){
total += parseInt($(this).val(), 10); //use radix 10 to ensure correct parseInt val
});
console.log(total);
});
</script>

On jsfiddle
<input name="price_1" id="price_1" type="text" value="50" />
<input name="price_2" id="price_2" type="text" value="40" />
<input name="price_3" id="price_3" type="text" value="20" />
<input name="price_4" id="price_4" type="text" value="10" />
<input name="price_5" id="price_5" type="text" value="80" />
var inputs = document.getElementsByTagName("input");
function sumIt() {
var sum = Array.prototype.reduce.call(inputs, function (a, b) {
return a + parseFloat(b.value);
}, 0);
console.log(sum);
}
Array.prototype.forEach.call(inputs, function (input) {
input.addEventListener("keyup", sumIt, false);
});

Related

How to check if value starts with and ends with either of 2 options using Javascript?

I have this current if statement - which is inside a for loop:
// Validate Temperatures
if(inputs[i].name.startsWith("actual-temp") || inputs[i].name.startsWith("min-temp") || inputs[i].name.startsWith("max-temp")) {
validate(parseFloat(inputs[i].value), inputs[i], e);
}
What it does
Checks all inputs that has name starting with actual-temp, min-temp and max-temp and passes them into a function called validate
My HTML file
<input type="number" name="max-temp-1">
<input type="number" name="max-temp-1">
<input type="number" name="max-temp-1">
<input type="number" name="min-temp-1">
<input type="number" name="min-temp-1">
<input type="number" name="min-temp-1">
<input type="number" name="actual-temp-1">
<input type="number" name="actual-temp-1">
<input type="number" name="actual-temp-1">
<input type="number" name="max-temp-2">
<input type="number" name="max-temp-2">
<input type="number" name="max-temp-2">
<input type="number" name="min-temp-2">
<input type="number" name="min-temp-2">
<input type="number" name="min-temp-1">
<input type="number" name="actual-temp-2">
<input type="number" name="actual-temp-2">
<input type="number" name="actual-temp-2">
<input type="number" name="max-temp-3">
<input type="number" name="max-temp-3">
<input type="number" name="max-temp-3">
<input type="number" name="min-temp-3">
<input type="number" name="min-temp-3">
<input type="number" name="min-temp-3">
<input type="number" name="actual-temp-3">
<input type="number" name="actual-temp-3">
<input type="number" name="actual-temp-3">
Question
Within my if statement - how can I grab all elements that startsWith() (as it is in the if statement currently) and ends with either -1 or -2? Or alternatively exclude inputs names that end with -3.
You can use regular expressions for your test
if (inputs[i].name.match(/^(actual|min|max)-temp-(1|2)$/)) {
validate(parseFloat(inputs[i].value), inputs[i], e);
}
Use str.includes
if(inputs[i].name.includes("actual-temp") || inputs[i].name.includes("min-temp") || inputs[i].name.includes("max-temp")) {
validate(parseFloat(inputs[i].value), inputs[i], e);
}
for (let item of my_list) {
if (item.charAt(item.length-1)!=="3"&&
(item.startsWith("actual-temp")|| item.startsWith("min-temp")||
item.startsWith("max-temp"))
) {
//logic goes here
}
}
when the first condition in the above if loop fails , javascript will not check the 3 items in OR statements (short circuiting comes into picture)

sum between one form to another form [duplicate]

This question already has answers here:
Number input. HTML
(3 answers)
Closed 3 years ago.
i make the sum between one form to another form and the number entered has a comma. I want to make an alert that cannot be input by letters. how can i do this?
input code
<input id="weight" class="form-control form-control-sm" type="text" name="weight" onkeyup="sum();" required />
<input id="runner" class="form-control form-control-sm" type="text" name="runner" onkeyup="sum();" required />
<input id="gross" class="form-control form-control-sm" type="text" name="gross" value="0" readonly />
this is my script
function sum() {
var txtFirstNumberValue = document.getElementById('weight').value;
var txtSecondNumberValue = document.getElementById('runner').value;
var result = parseFloat(txtFirstNumberValue) + parseFloat(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('gross').value = result;
}
}
Supposing that you are using modern web browser you will only need to do this:
<input id="weight" class="form-control form-control-sm" type="number" name="weight" onkeyup="sum();" required />
type="number" is sufficient.

How can I create new variables within a loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a form and I want to retrieve the values by their id's. Instead of writing var itemnamehere = document.getElementById('theid'); multiple times, I want to be able to loop through the inputs in the form and create variables within a for loop.
This is what I have so far
var gsItems = document.getElementsByClassName('gsinput').getAttribute('id');
for(var i = 0; i < gsItems.length; i++){
//create new variable here
}
Because getElementsByCLassName returns an nodelist you can't use getAttribute on it because that method is reserved for single elements only. BUT you also don't need the id either if I understand your question. You can simply iterate over the nodelist you get with getElementsByCLassName and do whatever you need to with the inputs, like grab their values.
Here's how you might approach it with ES6:
const gsItems = document.getElementsByClassName('gsinput');
[...gsItems].forEach(item => {
console.log(item.value);
});
<input class="gsinput" value="1" />
<input class="gsinput" value="2" />
<input class="gsinput" value="3" />
<input class="gsinput" value="4" />
<input class="gsinput" value="5" />
If you wanted to use ids you might want to create a map of ids against values. You could do something like this with reduce:
const gsItems = document.getElementsByClassName('gsinput');
const obj = [...gsItems].reduce((obj, item) => {
obj[item.id] = item.value;
return obj;
}, {});
console.log(obj);
<input class="gsinput" id="steve" value="1" />
<input class="gsinput" id="daisy" value="2" />
<input class="gsinput" id="tina" value="3" />
<input class="gsinput" id="dennis" value="4" />
<input class="gsinput" id="bob" value="5" />
And here's the ES5 method:
const gsItems = document.getElementsByClassName('gsinput');
Array.prototype.forEach.call(gsItems, function (item) {
console.log(item.value);
});
<input class="gsinput" value="1" />
<input class="gsinput" value="2" />
<input class="gsinput" value="3" />
<input class="gsinput" value="4" />
<input class="gsinput" value="5" />
Id is not perfect approach to get multiple form input values when using a loop.
function getSubmitValue(params) {
var formObject = document.theForm;
var itemnamehere = [];
if (formObject.length) {
for (var i = 0; i < formObject.length; i++) {
if (formObject[i].value !== "") {
itemnamehere.push(formObject[i].value);
}
}
} else {
alert("Please check your form input value")
}
}
<form id="myForm" name="theForm">
<input type="text" name="user" id="user" value="Arsalan" />
<input type="text" name="occopation" id="occopation" value="doctor" />
<input type="number" name="age" id="age" value="27" />
<input type="text" name="email" id="email" value="johndoe#test.com" />
<textarea name="message" id="message">Enter Your Message Her</textarea>
<button type="submit" onClick="getSubmitValue()">Place Order</button>
</form>

jQuery, How can I disable all others input field if sum of all values is greater "x"

jQuery, disable all others input on same class if sum of all value more than x
How to disable "HTML input box" which not empty node when the sum of any input box has value. I want to calculate some of any input field and disable any others if the sum is greater than x.
For example to this code:
second field = 5
forth field = 10,
sum is 15
first field and third field should be disabled
$('.inputReward').on('input',function() {
//$(this).next().not(this).prop('disabled', this.value.length)
var sum=0;
$('.inputReward').each(function () {
sum += +$(this).val();
if(sum>15) //15 is maximum value
$(this).next().not(this).prop('disabled', true);
else
$(this).next().not(this).prop('disabled', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="sRewards" value="" class="inputReward" />
<input type="number" name="sReward1" value="" class="inputReward" />
<input type="number" name="sReward2" value="" class="inputReward" />
<input type="number" name="sReward3" value="" class="inputReward" />
But now i just can do only disable all next input field of a last not empty node.
I think this is my best solution :)
$('.inputReward').on('input',function() {
//$(this).next().not(this).prop('disabled', this.value.length)
var sum=0;
$('.inputReward').each(function () {
sum += +$(this).val();
});
if(sum>=15)
$(this).siblings().not(this).prop('disabled', true);
else
$(this).siblings().not(this).prop('disabled', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="sRewards" value="" class="inputReward" />
<input type="number" name="sReward1" value="" class="inputReward" />
<input type="number" name="sReward2" value="" class="inputReward" />
<input type="number" name="sReward3" value="" class="inputReward" />

Get total of all input values with jQuery

I need the total of all the values from my input. The result must be displayed in the input field total that is readonly.
The user can enter 1 or more values. The problem is that my var value is not correct. I'd also like to know how I can return the value immediately by onchange?
$(document).ready(function() {
$("div#example input").change(function() {
var value = '';
$("div#example input[name!=total]").each(function() {
value += $(this).val();
});
console.log("value after each: " + value);
});
})
HTML:
<div id="example">
<input type="text" size="5" id="value1" name="value1" />
<input type="text" size="5" id="value2" name="value2" />
<input type="text" size="5" id="value3" name="value3" />
<input type="text" size="5" id="value4" name="value4" />
<input type="text" size="5" id="value5" name="value5" />
<input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" />
Try something like this:
$(document).ready(function() {
$("div#example id^='value'").change(function() {
var value = 0;
$("div#example input[name!=total]").each(function() {
var i = parseInt($(this).val());
if (!isNaN(i))
{
value += i;
}
});
$('#total').val(value);
});
})
use += parseInt($(this).val());
var sum = 0;
$('input[id^=value]').each (function(){ sum+=$(this).val(); });
$('#total').val( sum );
:]
I think this might be closer:
<script type="text/javascript">
$(document).ready(function() {
$("#example value").change(function() {
var total = 0;
$("#example value").each(function() {
total += parseInt($(this).val());
});
window.console && console.log("value after each: " + total);
});
})
</script>
<div id="example">
<input type="text" size="5" class="value" name="value1" />
<input type="text" size="5" class="value" name="value2" />
<input type="text" size="5" class="value" name="value3" />
<input type="text" size="5" class="value" name="value4" />
<input type="text" size="5" class="value" name="value5" />
<input type="text" size="5" id="total" readonly="readonly" class="bckground" name="total" />
</div>
Your original selector for $.change() was including the total box, which I suspect you don't want.
Am I correct in guessing you want to add numbers? Your original 'value' variable was a string.
And BTW, it's safer to use the 'window.console && console.log' idiom, since there won't be a console variable for many users. (Though I bet that line was only there for debugging.)
EDIT
Added parseInt() based on other suggestions.
Use the jQuery form serialization:
alert($("form_id").serialize());
There is also a comparison for different serialization types: http://jquery.malsup.com/form/comp/

Categories

Resources