0

I am using javascript to display an error when user click on form submit button if the number entered is not in between min and max. The issue is when you click submit button the form will submit regardless. Can you please look at the code below and tell me what I need to add. I need to prevent form from submitting if the min and max condition is not fulfilled.

html

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
        <script src="validation.js"></script></head>
<body>


<form name="form1" >
          <label>Enter Amount</label>
          <input id="amount" type="number"  value="0" min="5" max="10" step="1"/>
          <p id="error"></p>
          <br/>
          <label>Charity you wish to donate to</label>
          <input type="text" name="charity"></input>
          <br/>
          <button id="save_choice"  onclick="amountFunction()">Save Choice</button>
          <button><a href="#" target="_blank">Save Choice</a></button> 
            </form>

<p id="error"></p>

</body>
</html>

javascript

     var inpObj = document.getElementById("amount");
if (inpObj.checkValidity() == false) {
    document.getElementById("error").innerHTML = inpObj.validationMessage;
    return false
} else {
    document.getElementById("error").innerHTML = "Input OK";
    return true
} 

}

1 Answers1

-1

Taking advantage of the fact that you already have jQuery in the page, you can do it with the event listeners.

$("form[name=form1]").on("submit", amountFunction);

function amountFunction(ev){
     var inpObj = document.getElementById("amount");
     if (inpObj.checkValidity() == false) {
         ev.preventDefault();
         $("#error").text("Value should be between " + $(inpObj).attr("min") + " and " + $(inpObj).attr("max"));
         return false;
     } else {
         document.getElementById("error").innerHTML = "Input OK";
         return true;
     } 
}

Note: the event listener declaration should run when the page finished loading.

Juan Techera
  • 1,192
  • 2
  • 14
  • 25
  • Thank you soo much. that worked – user3043672 May 26 '16 at 20:01
  • I'm glad it worked. ;) – Juan Techera May 26 '16 at 20:25
  • I would like to output a error message like "Amount must be in between 1 and 10" but the two numbers min and max should not be hard coded instead value must come from within the min and max attribute inside html. It should be something like innerHTML = Amount must be between $(min) and $(max). Can you please advice. thanks – user3043672 May 26 '16 at 21:02
  • I've edited the answer to add the message, that should work. If it doesn't try changing $(inpObj).attr("min") for $(inpObj).prop("min") i can't remember if those are attributes or properties. – Juan Techera May 26 '16 at 21:11
  • Yes!! that worked. thanks once again – user3043672 May 26 '16 at 21:14