2013-04-11 137 views
8

当'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> 

回答

21

您需要返回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()" /> 

jsFiddle example

+3

快14秒,并与jsfiddle! +1你好 – 2013-04-11 16:27:47

+1

@ j08691非常感谢。 – Pawan 2013-04-11 16:36:48

+1

伟大的帮助。谢谢 :-) – 2017-03-22 07:51:42

1

制作empty()返回false时的形式不应该提交

3
<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> 
2

我有了这个,我想用它或许可以帮助

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

或用类或ID这样的工作

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

如果要保存代码,你可以简单地做:

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

我刚才说。