如何创建一个具有两种状态的按钮切换,其行为类似于表单输入的复选框

时间:2013-09-14 18:27:26

标签: javascript jquery html twitter-bootstrap

我想使用引导按钮(http://getbootstrap.com/javascript/#buttons)创建一个类似复选框的输入,有两种状态:

  • 显示“选择了选项A”的按钮;和
  • 另一个显示“选项B已选中”。

单击该按钮时,我希望它在这两个消息之间切换,但也能够将选择传递给表单。

最好的方法是什么?我的第一个想法是尝试标记data-toggle="button",但我不相信这是最简单的方法。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

这是Fiddle

<button id="switch" class="on"></button>
<span></span>

$('#switch').click(function() {

    $(this).val('100'); // Set the value of your choice

    if($(this).hasClass('on')) {
       $(this).toggleClass('off','on');
       $('span').text('Option A Selected and value is '+$(this).val());
    }
    if($(this).hasClass('off')) {
       $(this).val('200'); // Set the value of your choice
       $('span').text('Option B Selected and value is '+$(this).val());
    }        

});