我已阅读了很多帖子,并尝试了各种选项,但我对JavaScript的验证检查似乎没有运行。
我使用此post尝试编写验证检查以查看输入的邮政编码是否是一个传递到的邮件,但是当我运行它时没有任何反应,也没有出现任何警报。任何帮助表示赞赏。
这是我使用的JavaScript:
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes)){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
这是表格
<form name="zipForm" onsubmit="return(validateForm(zipCode))">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
答案 0 :(得分:1)
function validateZip() {
var zipCode = document.zipForm.zipCode.value;
var acceptableZipCodes = ["78205","72215","78212",];
for (i = 0; i < cars.acceptableZipCodes.length; i++) {
if(acceptableZipCodes[i] == zipCode{
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
}
答案 1 :(得分:1)
我会为您的表单标记使用ID而不是name属性(以便更快地检索)。
<form id="zipForm">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
然后在下面,我会这样做:
<script>
$(function() {
// add an event handler to your form (look at adeneo's comment)
$('#zipForm').on('submit', function(e) {
// prevent form from submitting
e.preventDefault();
// call your function
validateZip($("#zipCode").val());
});
function validateZip(zipCode) {
var acceptableZipCodes = ["78205", "72215", "78212"];
// be careful with using $.inArray as the return value for no
// matches is -1 (and not false)
if ($.inArray(zipCode, acceptableZipCodes) != -1) {
alert("Yes, we can help!");
} else {
alert("Sorry, we don't deliever to your area yet.");
}
}
});
</script>
答案 2 :(得分:1)
我发现有2个错误。 1,您定义函数validateZip,但您没有在脚本中调用它。 2,inArray()函数将返回数组中值的位置,所以当一个值不在数组中时,它将返回-1。
我在代码中做了一些更改。 希望对你有所帮助。
<form name="zipForm" onsubmit="return(validateZip())">
<input type="text" id="zipCode" name="zipCode">
<input id="user_info" type="submit">
</form>
<script type="text/javascript">
function validateZip() {
var zipCode = $("#zipCode").val();
var acceptableZipCodes = ["78205","72215","78212",];
if( $.inArray( zipCode, acceptableZipCodes) !== -1){
alert("Yes, we can help!");
}else{
alert("Sorry, we don't deliever to your area yet.");
}
}
</script>
答案 3 :(得分:0)