我在我的网站上使用此表单验证脚本:
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["name", "email", "country", "message",];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please enter a value in field";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
问题是我没有选择框的代码
任何人都可以给我验证选择框的代码吗? 我的选择框名称和ID是“国家/地区” 如果选择保留在“国家/地区”,我想要一个错误通知
答案 0 :(得分:1)
使用选定的选项属性
var country = $('#country option:selected').val();
代码循环将
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if(input.attr('id')== 'country' && $('#country option:selected').val() == "") {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
}else if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
答案 1 :(得分:0)
尝试
var cntry = $("#country").val();
if(empty(cntry))
{
alert('Select a country');
return false;
}
答案 2 :(得分:0)
您是否正在搜索http://jsfiddle.net/X5r8r/1109/
<select id="ddlViewBy">
<option value=""></option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<button id="submit"> submit </button>
$(document).ready(function(){
$("#submit").click(function(){
var select_box_value = $("#ddlViewBy").val();
if(select_box_value == ""){
alert('select value')
}else{
alert('success')
}
});
});