I have this code:
<form action="" id="credentials" method="post">
<label for="name" id="nameLabel" >Name*:</label>
<input type="text" name="name" id="name" value="" />
<select id="single">
<option value="0">Single</option>
<option value="1">Single2</option>
</select>
<input type="submit" value="Submit" name="" data-inline="true"/>
</form>
And I’m trying to validate like this:
$("#credentials").submit(function(e) {
var nameField = $("input#name").filter(function() {
return !$.trim(this.value).length;
});
if (nameField.length) {
nameField.css("border", "1px solid red");
alert("Name is missing!");
return false;
}
var stateField = $("#single").val();
if (stateField == 0) {
stateField.css("border", "1px solid red");
alert("State is missing!");
return false;
}
});
The input is working fine, but not the select. Any ideas? Here is a JSFiddle example
The problem is that your
stateFieldvariable holds the actual value of the field. It is not a reference to the field itself or a jQuery object for the field so you can’t saystateField.css().Try something like this:
Updated version of your demo: http://jsfiddle.net/A6eEh/3/
Note also that by returning from your function as soon as you find an error your validation will only ever report one error at a time (so the
stateFieldvalidation won’t occur unless you’ve entered a name).