如果可能,如何使用 jquery 和/或引导程序为多个选择制作可切换的 div?

Min*_*ark 1 html jquery widget multiple-choice twitter-bootstrap

我想制作一个漂亮的多选 HTML 页面。我想要 3 或 4<div>秒,包括图像和/或文本,用户应该能够<div>通过简单地点击任意位置来切换每个“开”或“关” <div>(如果可能的话,应该有一个突出显示的效果和动画) . 当表单被提交时,应该向服务器发送 each 的状态<div>,就好像它是一个复选框。

我已经搜索了所有地方,但找不到类似的东西。它看起来很基本,以至于我可能忽略了一些微不足道的东西。有任何想法吗?我已经在使用 jQuery 和 bootstrap,所以如果有一个仅基于这些框架的简单解决方案,我会很高兴。

谢谢。

编辑:我不希望<div>s 移动或消失。我只想要一个“突出显示”的效果,比如<div>选择时将背景颜色更改为蓝色,未选择时将背景颜色更改为白色。

Cym*_*men 5

我建议从一个好的 HTML 基础开始。我可能会在每个按钮中使用一个隐藏的单选按钮,divdiv在单击时选中或取消选中它。单选按钮将是表单上的有效项目,它将提交所选值。

HTML:

<div class="choice">
    <input id="choice_1" type="radio" name="choice" value="choice_1" />
    <label for="choice_1">Chicago</label>
</div>

<div class="choice">
    <input id="choice_2" type="radio" name="choice" value="choice_2" />
    <label for="choice_2">Los Angeles</label>
</div>


<div class="choice">    
    <input id="choice_3" type="radio" name="choice" value="choice_3" />
    <label for="choice_3">San Francisco</label>
</div>
Run Code Online (Sandbox Code Playgroud)

?JavaScript:

$(document).ready(function() {
    var choices = $('.choice');

    choices.on('click', function(event) {
        var choice = $(event.target);
        choice
            .find('[name="choice"]')
            .prop('checked', true)
            .trigger('change');
    });

    var inputs = $('.choice input');
    inputs.on('change', function(event) {
        var input = $(event.target);
        var choice = $(this).closest('.choice');

        $('.choice.active').removeClass('active');
        choice.addClass('active');
    });
});?
Run Code Online (Sandbox Code Playgroud)

演示:jsfiddle

替代方案:如果您想一次选择多个

因此,对于单选按钮,一次只有单选按钮组中的一个处于活动状态。如果这不是您想要的行为,您可以使用隐藏的复选框并打开和关闭它。

HTML:

<div class="choice">
    <input id="choice_1" type="checkbox" name="choice_1" value="choice_1" />
    <label for="choice_1">Chicago</label>
</div>

<div class="choice">
    <input id="choice_2" type="checkbox" name="choice_2" value="choice_2" />
    <label for="choice_2">Los Angeles</label>
</div>


<div class="choice">    
    <input id="choice_3" type="checkbox" name="choice_3" value="choice_3" />
    <label for="choice_3">San Francisco</label>
</div>
Run Code Online (Sandbox Code Playgroud)

?JavaScript:

$(document).ready(function() {
    var choices = $('.choice');

    choices.on('click', function(event) {
        var choice = $(event.target);
        var input = choice.find('[type="checkbox"]');
        input
            .prop('checked', !input.is(':checked'))
            .trigger('change');
    });

    var inputs = $('.choice input');
    inputs.on('change', function(event) {
        var input = $(event.target);
        var choice = $(this).closest('.choice');

        if (input.is(':checked')) {
            choice.addClass('active');
        }
        else {
            choice.removeClass('active');
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

演示:jsfiddle