代码之家  ›  专栏  ›  技术社区  ›  Toleo

如果表单中有任何内容被使用且不是空的,则发出警报

  •  0
  • Toleo  · 技术社区  · 8 年前

    $('form input').change(function(){
      if ($(this).val() != '') {
        alert('The Form Not Empty');
      } else {
        alert('The Form Empty')
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form method='get' action=''>
      <input type='text'>
      <input type='number'>
      <input type='checkbox'>
    </form>

    我想跟踪表单输入,如果整个表单输入为空,我会发出警报 空的 有一次,如果单个输入不为空,我会发出警报 不为空

    我一直在 Not Empty 在复选框上,但在 text 输入。

    如果表单不是完全空的,或者不是输入,我可以只跟踪表单本身吗?

    3 回复  |  直到 8 年前
        1
  •  2
  •   Sébastien    8 年前

    $(this).val() 不是复选框的良好测试,该值始终为“开”,不为空。

    对于需要使用的复选框 .prop()

    $('form input').change(function(event) {
      console.log($(this).val())
      if (event.target.type === 'checkbox') {
        if ($(this).prop('checked') === true) {
          console.log('checked');
        } else {
          console.log('not checked');
        }
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form method='get' action=''>
      <input type='text'>
      <input type='number'>
      <input type='checkbox'>
    </form>
        2
  •  0
  •   garritfra    8 年前

    HTML有一个内置功能,名为 required 提醒用户表单不应为空。对于您的表单,它应该如下所示:

    <form method='get' action=''>
      <input type='text' required>
      <input type='number' required>
      <input type='checkbox' required>
    </form>
    
        3
  •  0
  •   Saturnin    8 年前

    您可以使用 required 用于表单或输入的属性,使其成为必填项,更多信息 here .