Reputation: 289
I've looked through a bunch of posts and haven't found a solution that seems to work... getting kinda frustrated at this point, so I figured I'd see if someone else had a solution.
So, I'm trying to validate a field with the attribute "required" on a widget I'm creating, the problem being that when the user clicks the "create" button, it creates a new visible section and also duplicates it in a hidden section with the class "hide" for various reasons.
My validation code looks like this:
var $required = $("input[required]").css('border', '1px solid #CCC');
$invalid = $required.filter(function(){
return !this.value;
}).css('border', '1px solid red');
if($invalid.length){
alert('Please fill in all required fields');
} else {
//ajax call
}
This works just fine on all my other widgets, but since there is a hidden duplicate in this new widget, it passes on the visible fields but fails on the hidden fields.
My solution was to add a second part to "if" statement to search for whether invalid has a length AND if its parent element doesn't have the class "hide". However, changing the statement to the following doesn't seem to work:
if( $invalid.length && !$("input[required]").closest("li").hasClass("hide") ){
alert('Please fill in all required fields');
} else {
//ajax call
}
It seems to pass every time now...
The (general) structure of the element I'm trying to validate is - I removed most of the code, just to simplify it for viewing:
<li>
<div class="row-fluid>
<div class="span3">
<!-- Some content -->
</div>
<div class="span9">
<input type="text" required />
<input type="text" />
<input type="text" />
</div>
</div>
</li>
The hidden element follows the same structure, just it has
<li class="hide">
as the parent element, instead.
I assume there's something wrong in the syntax of my jQuery, but I've been trying to fix this issue for so long now that I'm probably just overlooking something super simple...
Thoughts? ;)
Upvotes: 1
Views: 1384
Reputation: 780842
Your if
statement is testing whether none of the required elements is in a hidden LI
, since hasClass("hide")
is true if any of the selected elements has the class.
You can use the :visible
pseudo-class in your selector so you only test the unhidden elements.
var $required = $("input[required]:visible").css('border', '1px solid #CCC');
or you can use search from the unhidden parents to find the required inputs.
var $required = $("li:not(.hide) input[required]").css('border', '1px solid #CCC');
or you can do the check in your filter function:
$invalid = $required.filter(function() {
return !this.value && !$(this).closest("li").hasClass("hide");
});
Upvotes: 3