2017-03-09 155 views
0

簡單的場景:獲取單選按鈕值選中或取消選中jQuery中

<div class="question_wrapper"> 
    <input type="text" class="new_question"> 
    <input type="checkbox" class="radioinput" name="new_questionActive[]"> 
</div> 

我試圖找出如何讓這個單選按鈕的具體數值,它是動態添加,每次我按下一個按鈕。

中的JavaScript至今:

$('.new_question').each(function() { 
    var active = $(this).parent().next(".radioinput").attr("checked") ? 1 : 0; 
} 

出於某種原因,它總是產生 「0」 值。我試圖與closest一起工作,試圖用siblings解決,與next ..但似乎沒有任何工作。

我需要非常接下來的.radioinput,它直接跟在之前的.new_question之後。

我在想什麼或做錯了什麼?

更新1

的建議,我改變attrprop,所以它看起來現在躺在這一點:

var active = $(this).parent().next(".radioinput").prop("checked") ? 1 : 0; 

但仍始終0

+1

變化'ATTR( 「選中」)'來'道具(「檢查」);' – Jer

+0

同樣的效果,仍然總是產生0 – DasSaffe

+0

使用'$(this).next()。prop(「checked」)? 1:0' – Mohammad

回答

1

由於:checkbox是當前的兄弟因此您需要使用當前元素使用.next()

var active = $(this).next(".radioinput").prop("checked") ? 1 : 0; 
 
console.log(active)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="question_wrapper"> 
 
    <input type="text" class="new_question"> 
 
    <input type="checkbox" class="radioinput" name="new_questionActive[]"> 
 
</div>

或者,你可以使用.find()目標後裔,而不是.next()

var active = $(this).parent().find(".radioinput").prop("checked") ? 1 : 0; 
 
console.log(active)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="question_wrapper"> 
 
    <input type="text" class="new_question"> 
 
    <input type="checkbox" class="radioinput" name="new_questionActive[]"> 
 
</div>

+0

這確實有效。感謝claryfing!我以爲我不明白爲什麼搬到父母那裏尋找'下一個'是行不通的。將盡快接受這一點。謝謝你,先生。 – DasSaffe