获取单选按钮值选中或取消选中jQuery中

问题描述:

简单的场景:获取单选按钮值选中或取消选中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

由于: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