根据值同步Checkbox可见性

时间:2012-10-02 15:13:04

标签: jquery checkbox

我有两个复选框组,我最终需要其中一个影响另一个的输出(可见性)。这是我的小提琴。

http://jsfiddle.net/kEKYw/1/

因此,第一个输入(int值)的值应该与第二个复选框组(当前隐藏)的输入值匹配,然后根据该选择显示它们。我觉得我非常接近,但正确方向的任何推动都将是一个巨大的帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

稍微修改了你的代码..请参阅代码注释。

DEMO: http://jsfiddle.net/kEKYw/3/

$("#wood_typeschecklist input").change(function() {
    var destEl = this.id.split("-");
    //a. Changed selector to look for starts with selector as the 
    //checkbox value returned is wood_type-<number> 
    //which doesn't match any existing id

    //b. `.split` splits the string when it matches its 
    //separator and so it was returning 3 tokens not 2 (in,wood_types,126)
    var $matchingElem = $("li[id^=" + destEl[1] + '-' + destEl[2] + "]", $("#acf-wood_species_availability"));
    ($(this).attr("checked") !== undefined) ? $matchingElem.show() : $matchingElem.hide();
});

答案 1 :(得分:1)

我相信你正在寻找this fiddle

// start off by hiding the second options
$("#acf-wood_species_availability li").hide();

//add a click method to the inputs
$("#wood_typeschecklist input").click(function() {
   //verify that it's checked, if so, show the other input of the same value (and check it also) 
   if ($(this).is(':checked')) {
        $('#acf-wood_species_availability input[value="' + $(this).val() + '"]').attr('checked', true).parents('.popular-category').show();
    }
    //if it's unchecked, hide the other input and uncheck this one
    else {
        $('#acf-wood_species_availability input[value="' + $(this).val() + '"]').attr('checked', false).parents('.popular-category').hide();                            
    }   
});

//now let's add click methods to the other checkboxes in case user clicks on them, if so, we hie this checkbox and uncheck the other one.
$("#acf-wood_species_availability input").click(function() {
    $(this).attr('checked', '').parents('.popular-category').hide();
    $('#wood_typeschecklist input[value="' + $(this).val() + '"]').attr('checked', false);
});