[英]Validate form before submitting to php
您好,我正在實現一個登錄頁面,從PHP方面來看一切正常,但是現在我將使用jQuery實現另一個功能:我想檢查登錄字段是否為空,是否要在頁面上打印一些內容,否則繼續用php,該怎么做?
這是我的HTML代碼的一部分:
<form id="loginForm" action="login-exec.php" name="loginForm" method="post" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label class="ui-input-text" for="login">Login:</label>
<input name="login" type="text" class="textfield" id="login" />
</div>
<div data-role="fieldcontain">
<label class="ui-input-text" for="password">Password:</label>
<input name="password" type="password" class="textfield" id="password"/>
</div>
<input type="submit" name="Submit" value="Login" />
</fieldset>
</form>
將事件綁定到表單的提交(注意:並非單擊提交按鈕)。 那就是您的代碼去檢查表單的地方,並在必要時阻止其發布。
$('#loginForm').on('submit', function(e){
if ($('#login').val()=='' || $('#password').val()==''){
e.preventDefault();
// alert('Fill in both fields');
// You can use an alert or a dialog, but I'd go for a message on the page
$('#errormsg').text('Fill in both fields').show();
}else{
// do nothing and let the form post
}
});
如果您希望顯示消息而不是使用對話框,請在頁面上某個位置(最好是在“提交”按鈕附近)添加errormsg div
<p id="errormsg" style="display:none;"></p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.