Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if at least one input field is filled in jQuery

I have a jQuery script that checks if at least one input field contains text but it doesn't check my select option. Can anybody please help me to implement it?

The script:

$(function(){
    $("#myform").submit(function(){

        var valid=0;
        $(this).find('input[type=text]').each(function(){
            if($(this).val() != "") valid+=1;
        });

        if(valid){
            alert(valid + " inputs have been filled");
            return true;
        }
        else {
            alert("error: you must fill in at least one field");
            return false;
        }
    });
});

and the HTML for testing this:

<form action="/echo/html" id="myform" method="post">
<input type="text"><br>
<input type="text"><br>
<input type="text"><br>

<select name="something" id="something" type="text">
<option value=""></option>
<option value="one">Option one</option>
<option value="two">Option two</option>
<option value="three">Option three</option>
</select>

<input type="submit"/>
</form>​
like image 913
L.S Avatar asked Nov 16 '12 12:11

L.S


1 Answers

For one statement to grab both 'select' and 'input' elements, simply change your single jQuery selector to a multiple selector, like so:

$(this).find('input[type=text], select').each(function(){
            if($(this).val() != "") valid+=1;
        });
like image 66
Delon Avatar answered Nov 11 '22 02:11

Delon