0
如何在我將文本框留空時提交提交警報,並且在提交時應該轉到下一頁。 必須回覆, 謝謝。提交Html/JavaScript時顯示提醒(文本字段爲空)
如何在我將文本框留空時提交提交警報,並且在提交時應該轉到下一頁。 必須回覆, 謝謝。提交Html/JavaScript時顯示提醒(文本字段爲空)
你可以試試這個:
HTML:
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(由你的目標頁面,你所說的 「下一頁」 之一的網址替換action屬性)。
JS(不的jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS(與的jQuery):
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
這裏是demo,基於jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
哪裏HTML/JavaScript代碼試圖改善? –
檢查[this](http://rickharrison.github.io/validate.js/)。將所需的規則應用於所有你想強制的領域。 – deepakb
請注意,@DeepakBiswal解決方案不支持所有[瀏覽器](http://www.w3schools.com/tags/att_input_required.asp) – litelite