DasSaffe
DasSaffe

Reputation: 2198

get radiobutton value checked or unchecked in jquery

Simple scenario:

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

I am trying to figure out on how to get to the specific value of this radio-button, which is dynamically added everytime I press a button.

The JavaScript so far:

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

For some reason, it always yields "0" as value. I tried to work with closest, tried to workaround with siblings, with next .. but nothing seem to work.

I need the very next .radioinput, which follows directly the prior .new_question.

What am I missing or doing wrong?

Update 1

as suggested, I changed attr to prop, so it does look lie this now:

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

But still always 0

Upvotes: 0

Views: 39

Answers (1)

Satpal
Satpal

Reputation: 133453

As :checkbox is sibling of current element so you need to use .next() with current element.

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>

OR, You can use .find() to target descendant, instead of .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>

Upvotes: 1

Related Questions