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>
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With