选中单选按钮时,jquery将类添加到元素

时间:2014-12-22 20:39:01

标签: jquery onchange addclass

当我检查单选按钮列表中的某个单选按钮时,我试图将“禁用”类添加到元素中。

这是我的(简化)html

<div id="input_layout" class="image ui-buttonset">

<div class="customizer-subtitle"></div>
    <input id="layout0" class="image-select ui-helper-hidden-accessible" type="radio" data-customize-setting-link="layout" name="_customize-radio-layout" value="0"></input>
    <input id="layout1" class="image-select ui-helper-hidden-accessible" type="radio" checked="checked" data-customize-setting-link="layout" name="_customize-radio-layout" value="1"></input>
    <input id="layout2" class="image-select ui-helper-hidden-accessible" type="radio" data-customize-setting-link="layout" name="_customize-radio-layout" value="2"></input>
    <input id="layout3" class="image-select ui-helper-hidden-accessible" type="radio" data-customize-setting-link="layout" name="_customize-radio-layout" value="3"></input>
    <input id="layout4" class="image-select ui-helper-hidden-accessible" type="radio" data-customize-setting-link="layout" name="_customize-radio-layout" value="4"></input>

</div>

这是我写的jquery:

$("#input_layout input").change(function() {
var layout_selection = $('#input_layout input[class="image-select"]:checked').val();
    if (layout_selection == '1') {
    $('#customize-control-site_style').addClass('disabled');
  }
});

在这个例子中,我试图将“禁用”类添加到#custom-control-site_style。目前,这根本不起作用。

2 个答案:

答案 0 :(得分:4)

您应该将事件附加到单选按钮类,然后使用this

$("input.image-select:radio").change(function() {
    if (this.value == "1") {
        $('#customize-control-site_style').addClass('disabled');
    } else {
        $('#customize-control-site_style').removeClass('disabled');
    }
});

答案 1 :(得分:0)

试试这段代码:

$("input.image-select:radio").click(function() {
    if (this.checked) {
        $('#customize-control-site_style').addClass('disabled');
    }
    else $('#customize-control-site_style').removeClass('disabled');
});