user1574598
user1574598

Reputation: 3881

Form validation index variable issue with Jquery

I'm having a strange problem trying to validate 8 radio buttons. It seems to be with the indexing. I am looping though 8 radio buttons in order to test if they are checked. If all 8 buttons are not checked, it will alert the user and event.preventDefault();

$("#form").submit(function(event) {

        var count = 0;

        for (var i = 0; i <= 7; i++) {
            var checked = $("input[type=radio][name=emotion]")[i].checked;
            if (!checked) {
                count = i;
            }
        }
        if (count == 7) {
            alert("You must select at least one emotional state!");
            event.preventDefault();
        }
    });

I've tried reconstrucing the same code in java and the condition count == 7 holds true, but nothing happens in my jquery.

Upvotes: 1

Views: 36

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You can just check for checked radio length:

$("#form").submit(function (event) {
    if(!$(":radio:checked").length) {
        alert("You must select at least one emotional state!");
        event.preventDefault();
    }
});

Upvotes: 1

Related Questions