当输入字段为空时阻止表单提交 [英] preventing form from submitting when input field is empty

查看:877
本文介绍了当输入字段为空时阻止表单提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当没有为'roll'输入字段提供值时,'empty()'函数会产生一个警告,但是这个空值仍然传递给'retrive.php',所以如何阻止这种情况发生并且只通过当提供某些输入值时,将值设为'retrive'.php。

when no value is provided to the 'roll' input field an alert is produced by the 'empty()' function but this empty value is still passed to 'retrive.php' so how to stop this from happening and only pass value to 'retrive'.php when some input value is provided.

<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才能取消提交。

You need to return false to cancel the submit.

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()" />

jsFiddle示例

jsFiddle example

这篇关于当输入字段为空时阻止表单提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆