简体   繁体   English

检查动态选择的单选按钮

[英]Check on a dynamically selected radio button

I am currently running Bootstrap with https://github.com/kflorence/jquery-deserialize and a modal. 我目前正在使用https://github.com/kflorence/jquery-deserialize和模式运行Bootstrap。 I use an AJAX call to grab the form from a php file and add it into the HTML form, deserialize data, and then open the modal. 我使用AJAX调用从php文件中获取表单,并将其添加到HTML表单中,反序列化数据,然后打开模式。 However, when working with a radio button, I can't use a separate jQuery script to check to see if the radio was checked. 但是,当使用单选按钮时,我无法使用单独的jQuery脚本来检查是否已选中单选按钮。 It always shows as false when checking with 使用进行检查时,始终显示为false

console.log($('#travel_only2').is(':checked'));

However, if I attempt to output the selector itself with 但是,如果我尝试输出选择器本身

console.log($('#travel_only2'));

then it will show as checked. 然后它将显示为选中状态。 How can I wait for the radio to get checked, or is there another option? 如何等待无线电检查,或者还有其他选择? Thanks! 谢谢!

UPDATE: also, I just attempted to use $('#travel_only2').is(':checked') in the console itself and it shows true. 更新:而且,我只是试图在控制台本身中使用$('#travel_only2').is(':checked') ,它显示为true。

UPDATE: I did away with the deserialize plugin and attempted this: 更新:我取消了反序列化插件,并尝试这样做:

$.each(this, function(name, val){
var $el = $('[name="'+name+'"]'),
type = $el.attr('type');

switch(type){
    case 'checkbox':
        $el.attr('checked', 'checked');
    break;
    case 'radio':
        $el.filter('[value="'+val+'"]').attr('checked', 'checked');
    break;
    default:
        $el.val(val);
}

}); }); Unfortunately using console.log(document.getElementById('travel_only2').checked); 不幸的是使用console.log(document.getElementById('travel_only2')。checked); shows false then typing into the console once everything is loaded shows document.getElementById('travel_only2').checked true 显示为false,然后在加载所有内容后键入控制台,显示为document.getElementById('travel_only2')。

LAST UPDATE: There seems to be a delay since the ajax call towards the template had the script included. 最后更新:由于对模板的Ajax调用包含了脚本,因此似乎有所延迟。 Instead, I used $.getScript into my main script to call the template script, and that worked perfectly. 相反,我在主脚本中使用$ .getScript来调用模板脚本,并且效果很好。

This is just pure javascript try this: 这只是纯JavaScript,请尝试以下操作:

if(document.getElementById('travel_only2').checked) {
      // radio button is checked
    }

EDIT 编辑

Since that didn't work try this one: 由于那不起作用,请尝试以下方法:

 if($('#travel_only2').prop('checked')){
//radio button is check
}

Fiddle showing the functions I am using. 小提琴显示我正在使用的功能。

http://jsfiddle.net/bgLYL/ http://jsfiddle.net/bgLYL/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM