[英]How to run HTML5 Validation with onClick JQuery function?
我正在嘗試在我的項目中實現HTML5驗證。 似乎非常有幫助且易於使用。 但是,僅當輸入類型設置為submit
此驗證才有效。 那部分給我造成了麻煩。 我有多種形式,並且在所有“提交”按鈕上使用相同的name
屬性。 所以我的函數看起來像這樣:
HTML:
<form name="myForm" id="myForm" method="POST" action="#">
<fieldset>
<legend>User Info</legend>
<div class="formItem">
<label for="last_name">Last Name:</label>
<input type="text" name="frmst_lname" id="frmst_lname" value="" size="20" maxlength="30" title="Maximum length 30 characters." required/>
</div>
<div class="formItem">
<label for="first_name">First Name:</label>
<input type="text" name="frmst_fname" id="frmst_fname" value="" size="20" maxlength="30" title="Maximum length 30 characters." required/>
</div>
//Same button I have on the other forms. Only ID is different.
<div class="formItem">
<p align="center"><input type="button" name="frmSubmit" id="frmstSubmit" value="Submit"></p>
</div>
</fieldset>
</form>
jQuery的:
$('input[name="frmSubmit"]').on('click', function(){
var frmID = $(this).closest('form').prop('id'); //take form ID
var processVal = $(this).attr('data-process'); //which process will be executed Add or Edit
//Here I would like to check form validation then process AJAX call
});
到目前為止,我無法通過onClick
函數使用HTML 5驗證。 我嘗試使用checkValidty()
但是我的表單上的必填字段始終沒有顯示消息。 我想知道HTML5是否適合我的項目,如何使驗證與onClick函數一起使用? 如果有人有解決此問題的方法,請告訴我。 提前致謝!
如果您希望HTML5驗證起作用,請更改按鈕類型以提交。
<input type="submit" name="frmSubmit" id="frmstSubmit" value="Submit">
如果要進行一些自定義驗證,請添加onsubmit屬性。
<form method="POST" action="form-handler" onsubmit="return checkForm(this);">
<p>Input: <input type="text" size="32" name="inputfield">
<input type="submit"></p>
</form>
<script type="text/javascript">
function checkForm(form)
{
if(!condition1) {
alert("Error: error message");
form.fieldname.focus();
return false;
}
if(!condition2) {
alert("Error: error message");
form.fieldname.focus();
return false;
}
...
return true;
}
</script>
請參閱: http : //www.the-art-of-web.com/javascript/validate/
如果您想通過HTML5驗證使用AJAX調用,請嘗試在on Submit函數中使用e.preventDefault() 。
$('#myForm').on('submit',function(e) {
e.preventDefault();
$.ajax({
url: url,
type: 'post',
data: data,
success: function (data) {
if (data.success) {
} else {
}
}
});
})
要么
$(document).on('submit','#myForm',function(e) {
e.preventDefault();
$.ajax({
url: url,
type: 'post',
data: data,
success: function (data) {
if (data.success) {
} else {
}
}
});
})
更新-添加以回答評論中的問題:
請參閱JSFiddle以將一個on change函數用於多種形式並獲取id屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.