Reputation: 3765
I've got a problem with my form validation: I have two DIV-container each with two answers. I would like to validate wheter there is minimum checked one radio or there is a value in one text element.
But my jQuery selector doesn't work:
HTML:
<div class="mandatory">
<input type="radio" value="1" name="answer1" /> Option 1
<input type="radio" value="2" name="answer1" /> Option 2
</div>
<div class="mandatory">
<input type="radio" value="1" name="answer2" /> Option 1
<input type="text" name="answer2" />
</div>
JS:
$('.mandatory').each(function(){
var elem = $(this).find('input:checked, input:text[value!=""]');
console.log(elem.attr('name')); //Always "answer2"
});
It returned the input element although it is empty. Here is my code: http://fiddle.jshell.net/Pisi2012/n9S2Y/
Thanks for your help!
Upvotes: 0
Views: 629
Reputation: 66
You could try Glyn Jones' solution from this other thread:
How can I select a hidden field by value?
So it might look something like this:
var elem = $(this).find('input:checked, input:text').filter(function () { $(this).val() != '' });
Upvotes: 0
Reputation: 388316
What I assume is you need the list of mandatory
divs, which does not satisfy the given condition, then try
var els = $('.mandatory').filter(function(){
var $this = $(this);
return !$this.find(':radio:checked').length && !$this.find(':text').filter(function(){return $.trim(this.value) != ""}).length
});
Demo: Fiddle
Upvotes: 0
Reputation: 318182
Your input doesn't have a value attribute, so the attributes selector matches, as the value isn't an empy string, there just is no value ?
Change
<input type="text" name="answer2" />
to
<input type="text" name="answer2" value="" />
Upvotes: 1
Reputation: 7063
Try this code :
$('.mandatory').each(function(){
var elem = $(this).find('input:checked, input[type="text"][value!=""]');
console.log(elem.attr('name')); //Always "answer2"
});
Upvotes: 0