jquery错误与返回布尔值
问题描述:
我是一个新手到javascript,我不能返回该函数的布尔值..我验证文本框为null,并返回false,如果它的空帮助请?jquery错误与返回布尔值
validateForm : function() {
$('.requiredField :input').each(function(){
if ('input[type=text]'){
if($(this).val().length === 0){
$(this).addClass('warning');
var errorMsg = $('<br /><span>Please Fill in the TextBox</span>').addClass('warning');
errorMsg.insertAfter(this);
$(errorMsg).css('color','red');
$('.warning').css('border-color','red');
//$(this).focus(function(){
//$(this).removeClass('warning');
//$(this).parent().children('span').remove();
//$(this).parent().children('br').remove();
//});
return false;
}
else
return true;
}
});
},
Form.validateForm(); // call to the function
答
您是return
荷兰国际集团从内的.each()
。这不会让你的函数返回一个值。
在.each()
循环,return false;
就像使用break;
,和return true;
就像使用continue;
。
您需要申报.each()
的变量外,设置里面其价值循环,然后返回它循环之后。
答
检查此行
if ('input[type=text]'){
应该
if($('input[type=text]')){
答
你可以试试这个:
$('.requiredField :input').each(function(){
var i=$(this).val();
if(i == '' || i == null)
{
//execute your codes
return false;
}else{
return true;
}
});
答
看来你正试图写一个插件?试试下面的代码:
(function($) {
$.fn.validateForm = function()
{
var formID = $(this).attr('id');
$('#'+ formID +' input[type=submit]').click(function(e)
{
e.preventDefault();
$('input[type=text]').each(function(){
if($(this).val().length === 0){
$(this).addClass('warning');
var errorMsg = $('<span>Please Fill in the TextBox</span>').addClass('warning');
errorMsg.insertAfter(this);
$(errorMsg).css('color','red');
$('.warning').css('border-color','red');
return false;
}else{
return true;
}
});
});
};
})(jQuery);
答
正如mentionned由@RocketHazmat,你的函数需要聚集来自内部循环的结果,为了验证有一个单一的出口点(并添加CSS类/ html元素)每输入。
你需要做这样的事情:
validateForm : function() {
var invalidInputs = [];
// only test the type='text' inputs
$('.requiredField :input[type="text"]').each(function() {
// if there is no value
if ($(this).val() == undefined || $(this).val().length == 0) {
$(this).addClass('warning');
var errorMsg = $('<br /><span>Please Fill in the TextBox</span>').addClass('warning');
errorMsg.insertAfter(this);
$(errorMsg).css('color','red');
$('.warning').css('border-color','red');
// add the invalid input to an array
invalidInputs.push($(this));
}
});
// The form is only valid for no invalid inputs were found.
return invalidInputs.length == 0;
}
你得到一个错误信息? – Kaf 2013-03-04 17:46:56
@Kaf没有消息或没有错误 – inputError 2013-03-04 17:47:59
返回false到哪里?你只是在执行这个函数。 – Popnoodles 2013-03-04 17:48:20