Overriding form submit based on counting elements with jquery.each

Posted by MrGrigg on Stack Overflow See other posts from Stack Overflow or by MrGrigg
Published on 2010-06-03T03:26:19Z Indexed on 2010/06/03 3:34 UTC
Read the original article Hit count: 219

Filed under:
|
|

I am probably going about this all wrong, but here's what I'm trying to do:

I have a form that has approximately 50 select boxes that are generated dynamically based on some database info. I do not have control over the IDs of the text boxes, but I can add a class to each of them. Before the form is submitted, the user needs to select at least one item from the select box, but no more than four.

I'm a little bit sleepy, and I'm unfamiliar with jQuery overall, but I'm trying to override $("form").submit, and here's what I'm doing. Any advice or suggestions are greatly appreciated.

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

$('.sportsCoachedValidation').each(function() {
    if ($('.sportsCoachedValidation :selected').text() != 'N/A') {
        sportsSelected++
    }                    
});

if (sportsSelected >= 1 && sportsSelected <= 4) {
    return true;
}
else if (sportsSelected > 4) {
    alert('You can only coach up to four sports.');
    sportsSelected = 0;
    return false;
}
else {
    alert('Please select at least one coached sport.');
    sportsSelected = 0;
    return false;
}

});

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about form