我想在用戶輸入數字或特殊字符時阻止提交數據。我用過這個。下面 防止提交
//restric entering numbers and special characters
function checkLetters() {
var crop = $('#crop').val().trim();
//Entering numbers
if (crop.match(/([0-9])/)) {
$('#cropEr4').show();
boolsub = false;
}
else {
$('#cropEr4').hide();
boolsub = true;
}
//Entering special characters
if (crop.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) {
$('#cropEr3').show();
boolsub = false;
}
else {
$('#cropEr3').hide();
boolsub = true;
}
}
//prevent submitting
function validateSubmit() {
var crop = $('#crop').val().trim();
if (crop !== "") {
$('#cropEr2').hide();
if (boolsub) {
boolsub = false;
return false;
}
if (boolsub) {
boolsub = true;
return true;
}
}
else {
$('#cropEr2').show();
return false;
}
}
是形式。
<form name="myForm" action="../controller/new.php" method="POST"
enctype="multipart/form-data" onSubmit="return validateSubmit()">
<table align="left" width="300" height="200">
<tbody>
<tr>
<td>Crop Name : </td>
<td><input type="text" name="crop_id" value=""size="45" id="crop" onkeyup="checkLetters(this.value);"/>
<div id="cropEr2" style="display:none;color:red">Enter crop name</div>
<div id="cropEr3" style="display:none;color:red">You cannot enter symbols, have to enter only letters.</div>
<div id="cropEr4" style="display:none;color:red">You cannot enter numbers, have to enter only letters.</div>
</td>
</tr>
<tr>
<td align="center">
<input class="button"type="reset" value="Clear Deatils" />
</td>
<td><input type="hidden" name="action" value="add_crop" />
<input class="button" id="submit" type="submit" value="Add Details" />
</td>
</tr>
</tbody>
</table>
誰能告訴我,爲什麼這不起作用?當我輸入數字和特殊字符時,顯示消息,但它仍然在提交表格。 我正在將此代碼加載到facebox中。
它看起來像'boolsub'需要在最外面的範圍。 – DevlshOne 2014-09-13 09:18:23
如果使用jQuery,請勿使用onclick/onsubmit屬性。使用jQuery連接事件。它允許多個處理程序,並且更容易維護代碼。 – 2014-09-13 09:21:54
查看你的JavaScript錯誤控制檯。它說什麼? (請注意,您可能必須對其進行配置,以允許消息自表單提交併加載新頁面以來持久存在)。 – Quentin 2014-09-13 09:26:20