2013-07-19 158 views
0

我的表单验证有问题: 我有两个DIV-容器,每个容器有两个答案。我想验证是否有最低限度检查一个无线电或有一个文本元素的值。选择器不起作用

但我的jQuery选择不工作:

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" 
}); 

它返回的输入元素虽然是空的。 这是我的代码:http://fiddle.jshell.net/Pisi2012/n9S2Y/

感谢您的帮助!

+0

元=输入,输入=文本和值不应该是空的 – alexP

+0

@Bondye:不完全。见http://api.jquery.com/text-selector – BoltClock

+0

answer2返回undefined,undefined不等于'' – Kayo

回答

0

试试这个代码:

$('.mandatory').each(function(){ 
    var elem = $(this).find('input:checked, input[type="text"][value!=""]'); 
    console.log(elem.attr('name')); //Always "answer2" 
}); 
1

您输入不具有价值属性,所以属性选择匹配,因为值不是empy串,那里只是没有价值?

变化

<input type="text" name="answer2" /> 

<input type="text" name="answer2" value="" /> 

FIDDLE

+0

'[value!=“”]'应该匹配':not([value])'。见http://api.jquery.com/attribute-not-equal-selector/ – BoltClock

+0

@BoltClock - 嗯,它不。添加一个值属性使它工作。 – adeneo

+0

@BoltClock - 在文档中它是':not([attr =“value”])',并且如果没有属性,它就不能匹配该值的空字符串,因为该值未定义 – adeneo

0

我认为是你所需要的mandatory div的,这不符合给定的条件列表,然后尝试

var els = $('.mandatory').filter(function(){ 
    var $this = $(this); 

    return !$this.find(':radio:checked').length && !$this.find(':text').filter(function(){return $.trim(this.value) != ""}).length 
}); 

演示:Fiddle

0

你可以从这个其他线程尝试格林·琼斯的解决方案:

How can I select a hidden field by value?

因此,它可能是这个样子:

var elem = $(this).find('input:checked, input:text').filter(function() { $(this).val() != '' });