3

I have this code in JS:

if($('.log input:checked')) 
    {
        alert('login checked');
        alert('do what you want');
    }
    else 
    {
    alert('login not checked');
        alert('you can not do what you want');
}

But it is not working correctly. IS the IF ELSE condition wrong?

4 Answers 4

5
if( $('.log input').is(':checked') ) { // true/false

You can use .is() in a jQuery fashion (it's descriptive) and will return a boolean against the matched element. But you can also use the JS .length property.

An even better solution (kindly suggested by @macek)

if( $('.log input').prop('checked') ) { // true/false
Sign up to request clarification or add additional context in comments.

3 Comments

Great, it is working, thanks a lot. After 7 minutes I will tick your answer ;), cause I have to wait.
jQuery has .prop() for this.
@macek after you left a comment actually realized "how could I miss that?!" :) thanks
0

Although using :checked is the preferred way of testing if a radio button is checked you could also simply check if $('.log input:checked') has any length.

if($('.log input:checked').length) {
    alert('login checked');
} else {
    alert('login not checked');
}

This is completely different from your if condition because length will either return the number of checked elements (indicating TRUE) or 0 (zero) indicating FALSE.

In your example if($('.log input:checked')) will always result in a non-FALSE result which should bring up the login checked message no matter if the radio button is checked or not.

Comments

0

You should actually be using .prop() for this. It will return a true|false value.

if ( $('.log input').prop('checked') ) { ...

http://api.jquery.com/prop/

Comments

0

try this small plugin:

Plugin:

(function($) {

    $.fn.eachChequed = function(fnc, fnnc) {

        var
            ck = $(this).filter('[type="checkbox"], [type="radio"]'),
            isFnc = $.isFunction(fnc),
            isFnnc = $.isFunction(fnnc);

        function callFnc(el) {
            if (isFnc) {
                return fnc.call(el);
            }
            return true
        }

        function callFnnc(el) {
            if (isFnnc) {
                return fnnc.call(el);
            }
            return true;
        }

        ck.each(function(i, el) {
            try {
                var r = $(el).is(':checked') ? callFnc(el) : callFnnc(el);
                return r;
            } catch (e) {}
        });
    };

})(jQuery);

Run:

$('input').eachChequed(function(){

    console.log('checked', $(this));

},function(){

    console.log('no checked', $(this));

});   

Test: link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.