skip to Main Content

I got 4 input boxes in html and I want to check if one or many of them are empty. The issue with this code is the fact that at each new submit when the check fails I receive an incremental number of alerts. Meaning, if first time validation for Value2 fails I receive 1 alert, then I insert a correct Value2 but Value3 is wrong so instead to display only one alert for Value3 I receive a bunch of 2 alerts, and so on for each new submit…

<script>
    function onSubmitNotification() {
        var checkThisOnes = ["Value1", "Value2", "Value3", "Value4"];
        $('#myform').submit(function() {
            for (i = 0; i < checkThisOnes.length; i = i + 1) {
                var checkedValue = $('#'+checkThisOnes[i]).val();
                if (checkedValue === undefined || checkedValue === "") {
                    alert("This field is empty: " + checkThisOnes[i])
                    return false
                }
            }
        });
</script>

2

Answers


  1. use event.preventDefault() on submit. This will stop default submit behavior.

    $('#myform').submit(function(event) {
       event.preventDefault()
       // .. rest of the code
    
      if(formvalid){ 
       // submit again
        $('#myform').submit()
      }
    })
    
    Login or Signup to reply.
  2. I don’t know why you need to use onSubmitNotification() but without that also it will work .Also,remove return false and use e.preventDefault() to avoid default submission.

    Demo Code :

    var checkThisOnes = ["Value1", "Value2", "Value3", "Value4"];
    $('#myform').on("submit",function(e) {
       var result=true; //to check
      for (i = 0; i < checkThisOnes.length; i = i + 1) {
        var checkedValue = $('#' + checkThisOnes[i]).val();
        if (checkedValue === undefined || checkedValue === "") {
          alert("This field is empty: " + checkThisOnes[i])
        result =false; //false don't submit
        }
    
      }
      console.log(result)
      return result; //returning true or false
    
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
    <form id="myform">
      <input type="text" id="Value1">
      <input type="text" id="Value2">
      <input type="text" id="Value3">
      <input type="text" id="Value4">
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search