Reputation: 339
After having successfully completed an application in Javascript, I am trying to make it more jQuery friendly. However, when I try to get the value of a radio button like so:
// relavent declarations:
var radio = $("[name='buttons']"); // 4 radio buttons
var val = '';
var score = 0;
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].val();
}
if(val === correct) {
score++;
}
What I'm trying to do is make it so that the equivalent in straight Javascript is like this:
for( var q in radio ) {
if (radio[q].checked)
val = radio[q].value;
}
if(val === correct) {
score++;
}
My Javascript console keeps giving me the error "Uncaught TypeError: Object # has no method 'val'" What is the problem?
Upvotes: 0
Views: 207
Reputation: 4946
As close as I think you want.
$(document).ready(function() {
var radio = $("input[type='radio']");
for (var i in radio) {
i = parseInt(i);
var r = radio[i];
if ($(r).prop("checked") == true) {
console.log($(r).val());
}
}
})
})
Added the readout of the value
Upvotes: 0
Reputation: 5038
i think you are writing some thing that have an answer and user if checked correct one then he will get a score
Suggestion 1) Give all the check box the same name , so that only one can be checked
<input type="radio" name="Answer" />
Suggestion 2) get the selected checkbox value from myForm
$('input[name=radioName]:checked', '#myForm').val()
Upvotes: 0
Reputation:
Try below code :
$(":radio:checked").each(function(){
val = $(this).val();
})
Upvotes: 1
Reputation: 18350
radio[q]
will give you a raw DOM node object, you probably want the associated jQuery object, so try radio[q].eq(q)
.
See: http://api.jquery.com/eq/
Upvotes: 1
Reputation: 40348
try this
$('input:radio').each(function(){
if($(this).is(':checked'))
var value = $(this).val();
});
Upvotes: 1