【问题标题】:Normal Buttons for ChoiceFieldChoiceField 的普通按钮
【发布时间】:2015-02-04 08:31:27
【问题描述】:

软件版本:我使用的是 Django 1.7 和 Python 3.4

我正在使用 Django 表单来处理用户输入验证和处理。在表单中,我有一个 ChoiceField,我想使用普通按钮而不是单选按钮或选择输入元素来显示它。我自己为模板编写html,而不是使用传递给模板上下文的表单来呈现html。

这是该字段的 HTML:

<form method="get" action=".">
    <div id="div_id_session_type">
        <div class="controls btn-group" role='group'>
            <input type="button" class='btn' name="session_type" id="id_session_type_1" value="Individual">
            <input type="button" class='btn' name="session_type" id="id_session_type_2" value="Small Group">
            <input type="button" class='btn' name="session_type" id="id_session_type_3" value="Class">
        </div>
    </div>
    <input class='btn' type="submit" value="Search">
</form>

当我在选择按钮后提交此表单时,该表单无法识别 session_type 字段(我的 ChoiceField)的任何输入。

但是,如果我将所有输入按钮上的 type="button" 更改为 type="radio",则表单将接受选择,但会将按钮变成单选按钮,这是我不想要的。

我怎样才能将选项保留为完整的按钮,并且仍然让表单接受输入?

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    如果没有 JavaScript,您将无法做到这一点。问题是&lt;input type="button"&gt; 元素在用户单击它们时不会改变状态。值没有被改变。您是否考虑过使用选择输入为用户提供下拉菜单?

    <form method="get" action=".">
    <div id="div_id_session_type">
        <div class="controls btn-group" role='group'>
            <select>
                <option value="individual">Individual</option>
                <option value="small_group">Small Group</option>
                <option value="class">Class</option>
            </select>
        </div>
    </div>
    <input class='btn' type="submit" value="Search">
    

    否则,您可以在使用 JavaScript 之后完成您的目标。您需要为每个按钮设置事件处理程序,并在单击按钮时更新一个值。

    【讨论】:

      【解决方案2】:

      我找到了一种解决方法,方法是使用隐藏的单选按钮并使标签显示为按钮。:

      <form method="get" action=".">
          <div id="div_id_session_type">
              <div class="controls btn-group" role='group'>
                  <label for="id_session_type_1" class="btn">Individual</label>
                  <input type="radio" class='hidden-radio' name="session_type" id="id_session_type_1">
                  <label for="id_session_type_2" class="btn">Small Group</label>
                  <input type="radio" class='hidden-radio' name="session_type" id="id_session_type_2">
                  <input type="radio" class='hidden-radio' name="session_type" id="id_session_type_3">
                  <label for="id_session_type_3" class="btn">Class</label>
              </div>
          </div>
          <input class='btn' type="submit" value="Search">
      </form>
      

      和 CSS

      input[type="radio"].hidden-radio {
        display: none;
      }
      

      我还让 jQuery 在单击时将 CSS 类添加到标签中,以更改所选标签的外观。这似乎运作良好。

      【讨论】:

        猜你喜欢
        • 2017-03-26
        • 2015-01-20
        • 2017-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-09
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多