简体   繁体   中英

Why does my form submit, when ignoring the popup alert

I have a form where no fields can be empty. I popup an alert box when user tries to submit the form with empty fields. but when user clicks on ok in the alert box the form get submitted.

Below is my code:

js:

 function checkIt(f)
  {   
    if (f.elements['username'].value=="" && f.elements['text'].value=="") {      
        alert('Both fields are required');
        return false;   
    } else {
        return true;
    } 
  }

form:

<form method="POST" action="" onSubmit="return checkIt(this)" id="submit">
    <input type="text" name="username" />
    <label>Enter Your Name</label>
    <input type="text" name="text" />
    <label>Enter Your Text</label>

<input type="submit" value="Submit Comment"/>
</form>

Action code:

$('.submit').submit(function(){

          $.ajax({
              url : ....,
              data : $(' form').serialize(),
              type: "POST",
              success : function(){
              }
          })

          return false;
      })

What I am doing wrong ?

if (f.elements['username'].value=="" && f.elements['text'].value=="") {

Because form submission prevents only if BOTH fields are empty. You should use OR(||) instrad of AND(&&)

Here is the code which works for me

 $('.submitComment').submit(function(){
      var username = document.getElementById("username").value;
      var text = document.getElementById("text").value;

      if (username != "" && text != "") {
          $.ajax({
              url : 
              data : $(' form').serialize(),
              type: "POST",
              success : function(){
              }
          })  
      } else {
          alert('Both fields are required');
      }

      return false;
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM