0

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.

1

3 Answers 3

1

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;
    }
};
Sign up to request clarification or add additional context in comments.

Comments

1

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");
}

1 Comment

@FelixKling if he's using js, he can use jQuery. It's never a bad thing to add it to a project, and if he can't use jQuery he'll make a comment here.
0

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;
   }
});

1 Comment

imho e.preventDefault() would be better than return false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.