简体   繁体   English

为什么忽略弹出式警报时提交表单

[英]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: 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. 因为仅当BOTH字段为空时才提交表单。 You should use OR(||) instrad of AND(&&) 您应该使用AND(&&)的OR(||)代数

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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