2013-04-11 132 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 !=''"/> 

我剛纔說。