Reputation: 520
Can anyone please tell what I am doing wrong with the following code?
<table>
<tr>
<td>
<input type="radio" name="rinput">$100 <br>
<input type="radio" name="rinput">$200 <br>
</td>
</tr>
</table>
<script>
$('table').click(function () {
$('input[type="radio"]').each(function() {
if($(this).is(':checked')) {
var text = $(this).nextUntil('br').text();
alert(text);
}
});
});
</script>
Basically I am trying to get text between current element "$(this)" and next element "br" if it's checked.
Upvotes: 1
Views: 67
Reputation: 36786
How is this? No HTML change neccessary:
$('table').click(function () {
text = $('input[type=radio][name=rinput]:checked')[0].nextSibling.nodeValue;
alert(text);
});
By the way, since there is only going to be one checkbox with the name=rinput
checked at once, your each()
method is redundant. I've used [name=rinput]:checked
in your selector instead.
Upvotes: 3
Reputation: 4700
$(this)
is your input, .nextUntil('br')
get the input and br and not the text node, .text()
get the content text of the input and the br.
If you really wanna go this way, put your text in spans or any other element.
<table>
<tr>
<td>
<input type="radio" name="rinput"><span>$100</span><br>
<input type="radio" name="rinput"><span>$200</span><br>
</td>
</tr>
</table>
<script>
$('table').click(function () {
$('input[type="radio"]').each(function() {
if($(this).is(':checked')) {
var text = $(this).nextUntil('br').text();
alert(text);
}
});
});
</script>
But i would also use value attribute.
Upvotes: 0
Reputation: 539
Why are you using value attribute i think you can easily get the value using jquery
<table>
<tr>
<td>
<input type="radio" name="rinput" value="$100"> <br>
<input type="radio" name="rinput" value="$200"> <br>
</td>
</tr>
</table>
Upvotes: 0