【问题标题】:Django/bootstrap form : how to set and get btn-group valueDjango/bootstrap 表单:如何设置和获取 btn-group 值
【发布时间】:2017-06-22 11:27:22
【问题描述】:

我是初学者,使用 Python/Django/bootstrap。我用谷歌搜索并没有找到我问题的完整答案(代码示例)。

在一个表单上,我想使用 3 个分组按钮来显示和选择警报系统的状态,可以是:武装/回家/未武装 我使用下面的 HTML 代码:

 <div class="btn-group btn-group-lg">
  <button class="btn btn-default" type="button">
  <em class="glyphicon glyphicon-lock"></em> Armed
  </button> 
  <button class="btn btn-default" type="button">
  <em class="glyphicon glyphicon-lamp"></em> Home
  </button> 
  <button class="btn btn-default" type="button">
  <em class="glyphicon glyphicon-home"></em> Unarm
  </button> 
</div>

问题是如何:

  1. 突出显示 3 按钮以显示警报状态 输入表格

  2. 获取用户修改的按钮状态(武装/家庭/非武装) 离开表格时

您是否可以向我提供更新的 HTML 代码以及要添加的 urls.py 和 views.py 的代码。

【问题讨论】:

    标签: html django twitter-bootstrap


    【解决方案1】:

    根据documentation你可以这样做:

    • 设置活动按钮:选择您感兴趣的按钮并添加活动类
    • 保持类处于活动状态:点击时,您只能为单击的按钮保留活动状态(从所有其他类中删除该类)
    • 获取活动按钮:选择具有活动类的按钮

    演示:

    //
    // set the second button active on DomReady
    //
    $('.btn-group-lg button').eq(1).addClass("active");
    
    
    //
    // Preserve the active status only for the clicked button
    //
    $('.btn-group-lg button').on('click', function(e) {
      $('.btn-group-lg button').not(this).removeClass("active");
      $(this).addClass("active");
    });
    
    
    //
    // get the active button
    //
    $('#btnGetActive').on('click', function(e) {
      var btnActive = $('.btn-group-lg button.active');
      console.log(btnActive.text().trim() + ' is the ' + btnActive.index() + ' active');
    })
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <div class="col-md-4">
        <button id="btnGetActive" class="btn btn-default" type="button">Get Active button</button>
    </div>
    
    <div class="btn-group btn-group-lg">
        <button class="btn btn-default" type="button">
            <em class="glyphicon glyphicon-lock"></em> Armed
        </button>
        <button class="btn btn-default" type="button">
            <em class="glyphicon glyphicon-lamp"></em> Home
        </button>
        <button class="btn btn-default" type="button">
            <em class="glyphicon glyphicon-home"></em> Unarm
        </button>
    </div>

    【讨论】:

    • 感谢您的帮助
    • 我修改了 $('.btn-group-lg button').eq(0)..... : $('.btn-group-lg button').eq( {{status}}) ...从我的 Pyhton 代码中传递“状态”参数。我必须将您的代码(脚本)放在我的 base.html 模板中才能使它们正常工作。我觉得这有点脏,想将它们添加到按钮所在的模板(main.html)中。如何在按钮所在的模板中使用这些脚本而不是base.html模板?
    • @MMGG 您打算在页面中使用的 js 必须包含在其中。我不使用 Python,但如果您想使用模板,请记住在您需要的任何地方包含 js 代码。我希望这会对你有所帮助。
    猜你喜欢
    • 2017-09-13
    • 2017-02-22
    • 1970-01-01
    • 2019-02-19
    • 2017-09-11
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多