引导单选按钮"Yes"或"No"不选取更改或单击事件



我有一组单选按钮,一旦选择了用户,它们就会通过AJAX加载。他们可以选择将其访问权限设置为"是"或"否",具体取决于是否需要。单击按钮时,将应用活动类,当我获得选中项的值时,它将返回预期值。

我遇到的问题是更改事件和单击事件,单击按钮时它们都不会触发?

.HTML:

<div class="col-md-4">
    <div class="btn-group" data-toggle="buttons" style="width:100%">
        <label class="btn btn-default <?php if($access['has_access']){?> active <?php } ?>" style="width:50%">
            <input type="radio" name="<?=$access['id']?>" id="option1" value="1" <?php if($access['has_access']){?> checked <?php } ?>>Yes
        </label>
        <label class="btn btn-default <?php if(!$access['has_access']){?> active <?php } ?>" style="width:50%">
            <input type="radio" name="<?=$access['id']?>" id="option2" value="0" <?php if(!$access['has_access']){?> checked <?php } ?>>No
        </label>
    </div>
</div>

.JS:

$(document).on('click', 'input[type="radio"]', function(){
    var data = {};
    data.access_id = $(this).attr('name');
    data.value = $(this).val();
    data.user_id = $('input[name="user_id"]').val();
    $.ajax({
        url: '/ajax/change_access.php',
        type: 'POST',
        cache: false,
        data: data,
        dataType: 'JSON',
        headers: {"cache-action":"no-cache"}
    }).done(function(data){
        console.log('here');
    }).fail(function(data){
        console.log("error");
    });
});

我尝试将目标更改为仅输入,但这对单选按钮没有影响,但由文本输入触发。可能缺少一些明显的东西,但看不到它,任何帮助将不胜感激。

注意:根据下面的评论,这在技术上是错误的/不必要的。尽管它仍然会附加事件。这不是附加事件的最佳方式。

(不正确的陈述;原始帖子(上面的代码只会在初始文档加载时附加事件。不是当 DOM 发生突变时(当您通过 AJAX 插入这些元素时(。这将解决您的问题:

$(document).on('DOMNodeInserted', function(e) {
   //You can use $(this) instead of $(e.target) if you'd like.
   if($(e.target).attr("type") === "radio") {
      $(e.target).click(function() {
        var data = {};
        data.access_id = $(this).attr('name');
        data.value = $(this).val();
        data.user_id = $('input[name="user_id"]').val();
        $.ajax({
            url: '/ajax/change_access.php',
            type: 'POST',
            cache: false,
            data: data,
            dataType: 'JSON',
            headers: {"cache-action":"no-cache"}
        }).done(function(data){
            console.log('here');
        }).fail(function(data){
            console.log("error");
        });
      });
    }
});

每次将新元素附加到 DOM 时都会触发此操作。我添加了一个检查以确保添加的元素是一个单选按钮。如果是这样,则将单击附加到它。

最新更新