防止在输入字段为空时提交表单

Preventing form submission when input field is empty

本文关键字:提交 表单 字段 输入      更新时间:2023-09-26

当没有向roll输入字段提供值时,empty()函数产生警报,但该空值仍传递给retrive.php。那么,我如何才能阻止这种情况的发生,并仅在提供某些输入值时将值传递给retrive.php ?

<html>
 <head>
   <title>STUDENT FORM</title>
    <script type="text/javascript">
        function empty()
        {
          var x;
          x = document.getElementById("roll-input").value;
          if (x == "") 
           { 
              alert("Enter a Valid Roll Number");
           };
        }
    </script>
</head>
 <body >
  <h1 align="center">student details</h1>       
    <div id="input">
      <form action='retrive.php' method='get'>
       <fieldset>
        <legend>Get Details</legend>
          <dl>
            <dt><label for="roll-input">Enter Roll Number</label></dt>
        <dd><input type="text" name="roll" id="roll-input"><dd>
            <input type="submit" value="submit" onClick="empty()" />
          </dl>
        </fieldset>
      </form>
    </div>  
  </body>
</html>

您需要返回false来取消提交。

function empty() {
    var x;
    x = document.getElementById("roll-input").value;
    if (x == "") {
        alert("Enter a Valid Roll Number");
        return false;
    };
}

<input type="submit" value="submit" onClick="return empty()" />
<<p> jsFiddle例子/strong>

如何使用所需的属性?

<input id="Name" name="Name" class="form-control" placeholder="Enter name" type="text" required/>

只适用于html5

最简单的方法是在

输入标签中添加属性"required"
<input type="text" name="name" required>
<form method="post" name="loginForm" id ="loginForm" action="login.php">
<input type="text" name="uid" id="uid" />
<input type="password" name="pass"  id="pass" />
<input type="submit" class="button" value="Log In"/>
<script type="text/javascript">
$('#loginForm').submit(function() 
{
    if ($.trim($("#uid").val()) === "" || $.trim($("#pass").val()) === "") {
        alert('Please enter Username and Password.');
    return false;
    }
});
</script>
</form>

我用这个,我想它可能会有帮助

  $(function () {
        $('form').submit(function () {
            if ($('input').val() === "") {
                alert('Please enter Username and Password.');
                return false;
            }
        });
    })

或者像这样处理类或ID

$('.inputClass')
$('#inputID')

如果您想保存代码,您可以简单地执行:

<input type="text" name="roll" id="roll-input">
<input type="submit" value="submit" onClick="return document.getElementById('roll-input').value !=''"/>

我只是说。