Reputation: 5118
I have a <input type="text" name="value"/>
in a loop.
<%for (i=0;i<10;i++){%>
<input type="text" name="value"/>
<%}%>
<input type="button" name="submit">
On submit I need to check the input variables(10 boxes) should not exceed the value of 100.
Please let me know how to call a JS and send these 10 values to it and compare the sum with 100.
Upvotes: 0
Views: 2549
Reputation: 816404
To give a proper JavaScript answer:
Get a reference to your form:
var form = document.getElementById('formId');
Bind an event handler for the submit event, e.g.:
form.onsubmit = function() {...};
Inside the handle, get a reference to all input elements with name value
:
var inputs = this.elements['value'];
Iterate over the elements and sum their values:
var sum = 0;
for(var i = 0, len = inputs.length; i < len; i++) {
sum += +inputs[i].value;
}
Stop the default action if the sum is larger than 100:
if(sum > 100) {
return false;
}
Complete example:
var form = document.getElementById('formId');
form.onsubmit = function() {
var inputs = this.elements['value'],
sum = 0, i, len;
for(i = 0, len = inputs.length; i < len; i++) {
sum += +inputs[i].value;
}
if(sum > 100) {
return false;
}
};
Upvotes: 1
Reputation: 5917
Extending on @marcgg's answer:
$("form").submit(function () {
total = 0;
$("#inputs input").each(function(){
total += parseInt($(this).val());
});
alert("You have a total value of" + total);
if(total > 100){
alert("It's more than 100, I should do something here");
return false;
}
});
Upvotes: 0
Reputation: 66436
Wrap everything in a div for scope's sake
<div id="inputs">
// Your code
</div>
Then you can loop
total = 0;
$("#inputs input").each(function(){
total += parseInt($(this).val());
});
alert("You have a total value of" + total);
if(total > 100){
alert("It's more than 100, I should do something here");
}
Upvotes: 1