2016-09-15 119 views
1

我有一组单选按钮,第一个是在呈现html时静态设置的。其余的是使用jQuery动态创建的。创建单选按钮下面的代码如何检测jquery中单选按钮的检查状态?

for (var i = 1; i < length; i++){ 
     $('.radio').append('<br>'); 
     $('.radio').append('<label><input type = "radio" id = '+options[i]+' value = '+i+' name = "options" class = "radio-options"/><p>'+options[i]+'</p></label>'); 
    } 

    //creating the last radio button here 
    $('.radio').append('<br>'); 
    $('.radio').append('<label><input type = "radio" id = "Custom" value = '+length+' name = "options" class = "radio-options"/><p>Custom</p></label>') 

给予我有一个提交按钮,当我点击,我要检查它的单选按钮具有checked属性的属性。这是我的尝试。

$('.submit-butt').on('click', function(){ 

我在调用提交按钮点击处理程序后立即打印所有单选按钮的checked属性状态。无论我是否选择了单选按钮,它们都是错误的。

    for(var i = 0; i < options_length; i++){ 
         console.log($('input:radio[name=options]').prop('checked')); 
        } 


        if($('input:radio[name=options]').prop('checked', true)){ 
         console.log('Found my value'); 

         var _this = $('input:radio[name=options]:checked'); 

但是,由于某种原因,这个控制台日志语句打印出定制的ID,这是最后一个单选按钮的id,即使我没有选择它。

console.log(_this.attr('id')); 

这里是我第二次打印所有单选按钮的checked属性的地方。它在这里也是错误的,包括在前一行打印出来的Custom id单选按钮。

     for(var i = 0; i < options_length; i++){ 
         console.log($('input:radio[name=options]').prop('checked')); 
        } 
        } 
       }); 

无论我是否选择一个单选按钮与否,也不论哪个单选按钮,当我点击提交按钮,自定义单选按钮立即选择,即使该电台的检查财产按钮仍然打印为false。我该如何解决这个问题?

+0

O'boy,首先是什么'options_length'?其次'if($(element).prop('checked',true))...'总是为真,并且不检查是否被检查,**它将**选中的属性设置为true并返回一个jQuery集合。 – adeneo

+0

可能的重复[如何检查复选框是否在jQuery中检查?](http://stackoverflow.com/questions/901712/how-to-check-if-a-checkbox-is-checked-in-jquery) – Liam

+0

'$('input:radio [name = options]')。prop('checked',true)'**设置**检查过的道具不会检查是否检查过你要$'('input:radio (':checked')'或'$('input:radio [name = options]')。prop('checked')== true' – Liam

回答

0

你应该引号添加到的ID和动态创建的单选按钮的其他属性:

for (var i = 1; i < length; i++){ 
     $('.radio').append('<br>'); 
     $('.radio').append('<label><input type = "radio" id = "'+options[i]+'" value = "'+i+'" name = "options" class = "radio-options"/><p>'+options[i]+'</p></label>'); 
    } 

    //creating the last radio button here 
    $('.radio').append('<br>'); 
    $('.radio').append('<label><input type = "radio" id = "Custom" value = "'+length+'" name = "options" class = "radio-options"/><p>Custom</p></label>') 
+0

这是要解决我的问题问题,还是只是与良好的编码做法有关? –

+0

@ZaidHumayun - 这是修复的一半。报价不是可选的。你需要他们。 –

0

不要忘记引号..

$('.radio').append('<label><input type = "radio" id = "'+options[i]+'" value = "'+i+'" name = "options" class = "radio-options"/><p>'+options[i]+'</p></label>'); 

尝试这样的事情。

for(var i = 0; i < options_length; i++){ 
    console.log($('#'+options[i]).is(':checked')); 
} 
+0

因此,我添加了引号,并尝试使用if语句的版本。是(':checked'),但没有for循环,它似乎检测我是否现在选择了一个单选按钮。现在,我如何检测选中哪个单选按钮而不通过for循环运行? –

+0

哦,我明白你为什么使用名字。使用'$(“input [name ='options']”)。is(“:checked”)'@ZaidHumayun –

相关问题