开发者

isset in jQuery

I want check if there is class .required_selectbox in html code run function required_selectbox() and if 开发者_开发百科there is class .required in html code run function required_valid(), after submit, how is it?

function required_valid() {
    $('.required').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            $(this).css("background", "#FFFFEC");
            result = true;
        }
        $(this).keyup(function () {
            $(this).css("background", "#FFFFEC");
        })
    });
    return result;
}

function required_selectbox() {
    $('.required_selectbox').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            result = true;
        }

    });
    return result;
}
$('.submit').submit(function () {
    //alert('hello');
    var passed = true;
    passed = required_selectbox() && passed;
    passed = required_valid() && passed;
    if (!passed) {
        return false;
    }
});


A simple approach would be to run those functions even if the elements aren't there. Because no elements would be found, the calls to each() would do nothing, so all that's needed is to have the result variable set to true by default:

function required_selectbox() {
    var result = true;  // <--- 
    $('.required_selectbox').each(function () {
        if (!$(this).val()) {
            //var cssObj=;
            $(this).css("background", "#ffc4c4");
            result = false;
        } else {
            result = true;
        }
    });
    return result;
}

Also, it looks like you probably don't want the else statement in there so you might want to remove it.


I'm not sure hat you want, but -

 $('.required_selectbox').length

would let you know if there were any elements of class .required_selectbox in your document. You could then do a similiar thing for required_valid


function required_valid() {
    var required = $('.required');
    required.css("background", "#FFFFEC");

    //Find any empty elements, and add the red style
    var empty = required.filter(function() {
        return $(this).val() == '';
    });
    empty.css("background", "#ffc4c4");

    //Did we find any empty elements?
    return empty.length > 0;
}

function required_selectbox() {
    var required = $('.required_selectbox');
    required.css("background", "#FFFFEC");

    //Find any empty elements, and add the red style
    var empty = required.filter(function() {
        return $(this).val() == '';
    });
    empty.css("background", "#ffc4c4");

    //Did we find any empty elements?
    return empty.length > 0;
}

$('.submit').submit(function() {
    return required_selectbox() && required_valid();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜