[英]Preventing form submission when input field is empty
当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()" />
如何使用 required 属性?
<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 !=''"/>
我只是说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.