8

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>​

1 Answer 1

11

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;
        });
Sign up to request clarification or add additional context in comments.

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.