0

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?

4

5 回答 5

1

try this

$('input:radio').each(function(){
   if($(this).is(':checked'))
     var value = $(this).val();
});
于 2013-03-22T01:18:41.140 回答
1

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/

于 2013-03-22T01:19:07.163 回答
1

Try below code :

$(":radio:checked").each(function(){
    val = $(this).val();
})
于 2013-03-22T01:19:17.007 回答
0

我认为你正在写一些有答案的东西,如果用户检查正确,那么他会得到一个分数

建议 1)给所有的复选框起相同的名字,这样就只能选中一个

 <input type="radio" name="Answer" />

建议 2)从 myForm 中获取选中的复选框值

 $('input[name=radioName]:checked', '#myForm').val()
于 2013-03-22T01:23:55.440 回答
0

尽可能接近我认为你想要的。

 $(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());
                    }
                }

            })
 })

添加了值的读数

于 2013-03-22T01:34:07.127 回答