Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a form has input elements using jQuery

I'm developing an application using Yii PHP framework, and I'm using jQuery for form validation. I have a page with a form on it which contains checkboxes for its input elements.

However these checkboxes are dynamically created depending on the entries.

To better understand it, I'm making a crossing matrix, a table basically, having rows for feemales and columns for males, and defining checkboxes in the cells where there are intersections. Literally a crossing matrix for male and female individuals.

However if there are no males and females that are defined to be crossed yet, then as for validation, it should not allow the user to submit.

My problem is how do I know whether a form has no elements?

And if there are checkbox elements, how can I catch whether or not the user has checked at least one of them?


Here is what I have tried, but it doesn't seem to catch it, the form still submits data, I wonder why:

$('#crossingMatrixForm').submit(function() {

       $(":input").each(function() {
           if ($(this).val() === empty()) {
               alert("form empty!");
               return false;
           }
       });

});
like image 775
muffin Avatar asked Feb 15 '23 03:02

muffin


1 Answers

You can see if at least one checkbox exists in the form and is checked with

$('#crossingMatrixForm').submit(function(){    
    if (!$(this).find("input:checked").length) {
        alert("form empty!");
        return false;
    }
});

If you want to disambiguate between "no checkboxes exist" and "at least one exists, but none are checked" you can use $(this).find(":checkbox") for the former and .filter(":checked") on that for the latter. In both cases, use .length to see if at least one control exists:

$('#crossingMatrixForm').submit(function(){    
    var checkboxes = $(this).find(":checkbox");
    if (!checkboxes.length) {
        alert("form empty!");
        return false;
    }
    else if (!checkboxes.filter(":checked").length) {
        alert("none selected!");
        return false;
    }
});
like image 146
Jon Avatar answered Feb 24 '23 16:02

Jon