2012-09-28 67 views
0

所以我有一个下拉列表和几个复选框。下拉列表属于用户只能选择一个选项的主要选择。复选框属于第二选择,用户可以根据需要选择尽可能多的选项,但从下拉列表中选择的选项不会显示为选项之一。这是我的代码到目前为止:fiddleHTML/jquery隐藏+显示依赖项

因此,例如,如果用户从下拉列表中选择选项1,则只有选项2-8应作为复选框可用。我想从本质上隐藏option1并显示其余部分。我真的不知道这是叫什么,所以我不知道要搜索什么或在哪里寻找。我正在查看是否有一些jQuery插件,但我应该怎么做呢?由于

回答

1

迈克尔,试试这个:

的JavaScript

$(function(){ 
    $('#primary').on('change', function() { 
     var $sec = $('.secondary'); 
     var idx = this.selectedIndex; 
     $sec.find('input').attr('disabled', false).eq(idx).attr('disabled', true); 
     $sec.find('label').removeClass('disabled').eq(idx).addClass('disabled'); 
    }).trigger('change'); 
}); 

CSS:

.disabled { 
    color: gray; 
} 

Demo

我已经通过禁用,而不是隐藏不需要的复选框略有偏离。这对用户来说可能不那么令人困惑。如果没有,那么它很容易修改代码隐藏/显示:

$('#primary').on('change', function() { 
    $('.secondary').find('label').show().eq(this.selectedIndex).hide(); 
}).trigger('change'); 

Demo

1

Check this DEMO

你不需要为它的一个插件。简单的jQuery的应该是足够的

试试这个

$('#primary').on('change', function() { 
    // Show all the options initially 
    $('.secondary label').show(); 
    // Get the currently selected option 
    var selected = $(this).val(); 
    // Hide the label that encases the option 
    $('.secondary').find('input[type="checkbox"][value="'+ selected + '"]').closest('label').hide(); 

}).change();​ 

更新的代码

为此,您需要创建复选框的模板,可以在选择变更时用于填充设计ES ..

$('#primary').on('change', function() { 
    // Clone the checkbox template 
    var $template = $('.template').clone(); 
    var selected = $(this).val(); 
    // Remove the selected option from cloned object 
    $template.find('input[type="checkbox"][value="'+ selected + '"]').closest('label').remove(); 

    // Append to the DropDown 
    $('.secondary').html($template.html()); 

}).change();​ 

UPDATED FIDDLE

+0

有没有一种方法来收集所有的选择框,而不是有隐藏的元素的差距? –

+0

检查上面的帖子..更新它 –

+0

由于某种原因,这不工作在我的网页,它仍然有一个空白,删除元素是。有任何想法吗? –