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

How to create a button toggle with two states, that behaves like a checkbox for form input

本文关键字:类似于 复选框 输入 表单 按钮 创建 状态 两种 何创建      更新时间:2023-09-26

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

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

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

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

这是一个小提琴

<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());
    }        
});