2013-07-19 161 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() != '' });