在javascript中使用标记'继续'?

时间:2016-09-01 09:06:14

标签: javascript jquery

我想在填写所有字段后才触发submit_form函数。现在提交表格将被触发。

$('#submit').click(function() {
  $('body input').each(function() {
    if ($(this).val() == '') {
      alert('Please fill in ' + $(this).attr('placeholder'));
      $(this).focus();
      return false;
    }
  })

  submit_form();
});

function submit_form() {
  alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <input type="" placeholder="name">
  <br>
  <br>
  <input type="text" placeholder="hp">
  <br>
  <br>
  <input type="text" placeholder="email">
  <br>
  <br>
  <button id="submit">Submit</button>
</body>

4 个答案:

答案 0 :(得分:1)

好的,根据您的代码,您的提交功能总是调用,所以我为它添加了一个标志,请检查....

$('#submit').click(function() {
    var flag = 1;
    $('body input').each(function() {
        if ($(this).val() == '')
        {
            alert('Please fill in ' + $(this).attr('placeholder'));
            $(this).focus();
            flag = 0;
            return false;
        }
    })
    if(flag)
    {
        submit_form();
    }
});

答案 1 :(得分:0)

使用标记阻止在一个输入字段为空时提交表单。

$('#submit').click(function() {
  this.canSend = true;
  $('body input').each(function() {
    if ($(this).val() == '') {
      this.canSend = false;
      alert('Please fill in ' + $(this).attr('placeholder'));
      $(this).focus();
      return false;
    }
  })
  if (this.canSend) {
    submit_form();
  }
});

function submit_form() {
  alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="" placeholder="name">
<br>
<br>
<input type="text" placeholder="hp">
<br>
<br>
<input type="text" placeholder="email">
<br>
<br>
<button id="submit">Submit</button>

此处还提供了重构版本: https://jsfiddle.net/j74u8wvL/

答案 2 :(得分:0)

试试这个

$('#submit').click(function() {
    var flag = 1;
    $('body input').each(function() {
        if ($(this).val() == '')
        {
            alert('Please fill in ' + $(this).attr('placeholder'));
            $(this).focus();
            flag = 0;
            return false;
        }
		else
		{
			 flag = 1;
		}
    })
    if(flag)
    {
        submit_form();
    }
});

function submit_form() {
  alert('proceed to sumbit form.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <input type="" placeholder="name">
  <br>
  <br>
  <input type="text" placeholder="hp">
  <br>
  <br>
  <input type="text" placeholder="email">
  <br>
  <br>
  <button id="submit">Submit</button>
</body>

答案 3 :(得分:0)

删除所有JavaScript。

<body>
  <input type="text" placeholder="name" required>
  <br>
  <br>
  <input type="text" placeholder="hp" required>
  <br>
  <br>
  <input type="email" placeholder="email" required>
  <br>
  <br>
  <button id="submit">Submit</button>
</body>