0

Given this HTML code:

<body onload="assessSum()">
        
        <input type="number" id="num0" min="0" max="10">
        <input type="number" id="num1" min="0" max="10">
        <button type="submit" id="sub">Submit</button>

</body>

What would be a function that would disable the submit button, if the sum of the 2 input fields is greater than a certain value?

My JavaScript/Jquery code doesn't seem to work:

function assessSum(){
    var total = 0;
    var maximum = 5;
    var bt = document.getElementById('sub');
    $.each($("input"),function(){
        total += parseInt($(this).val()) || 0;
      });
      if(total > maximum){
          bt.disabled = true;
      }
      else{
          bt.disabled = false;
      }

}
2
  • 1
    So where are your event listeners? You need to check it onchange of the inputs Commented May 6, 2021 at 14:59
  • @epascarello I was able to make use of event listeners for a value of one input. When I added more, the problem occured. After a bit of googling, I opted for Jquery. Needless to say, that itself didn't solve the problem. So I posted my question. Commented May 6, 2021 at 15:04

1 Answer 1

1

You need to run the function on change event of the inputs.

$(':input').on('change', assessSum);

function assessSum() {
  var total = 0;
  var maximum = 5;
  var bt = document.getElementById('sub');
  $("input").each((i, el) => {
    total += (parseInt(el.value) || 0);
  });
  
  if (total > maximum) {
    bt.disabled = true;
  } else {
    bt.disabled = false;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="num0" min="0" max="10">
<input type="number" id="num1" min="0" max="10">
<button type="submit" id="sub">Submit</button>

The disabling can also be done like this:

$('#sub').attr('disabled',  (total > maximum));
Sign up to request clarification or add additional context in comments.

Comments

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.