如何绑定引导按钮复选框和表单

How to bind bootstrap button-checkbox and form?

本文关键字:按钮 复选框 表单 何绑定 绑定      更新时间:2023-09-26

有一个代码如下所示:

<form action="/test.html" method="get">
    <p><b>Question?</b></p>
    <p><input type="radio" name="answerswer" value="a">C<Br>
       <input type="radio" name="answerswer" value="b">B<Br>
       <input type="radio" name="answerswer" value="c">C</p>
    <div class="btn-group" data-toggle="buttons-checkbox">
    <button type="button" name="bb" value="b1" class="btn btn-primary">Left</button>
    <button type="button" name="bb" value="b2" class="btn btn-primary">Middle</button>
    <button type="button" name="bb" value="b3" class="btn btn-primary">Right</button>
    </div>
    <p><input type="submit"></p>
</form>

如何将其发送到get方法?可能需要编写一些js(jquery)代码,但我什么都写不出来。

您遇到的问题是没有提交按钮值。

以下内容将为提交表单时选择的按钮创建隐藏的输入元素。

<form action="/test.html" id="the-form" method="get">
    <p><b>Question?</b></p>
    <p><input type="radio" name="answerswer" value="a">C<Br>
       <input type="radio" name="answerswer" value="b">B<Br>
       <input type="radio" name="answerswer" value="c">C</p>
    <div class="btn-group" data-toggle="buttons-checkbox">
        <button type="button" name="bb1" value="b1" class="btn btn-primary">Left</button>
        <button type="button" name="bb2" value="b2" class="btn btn-primary">Middle</button>
        <button type="button" name="bb3" value="b3" class="btn btn-primary">Right</button>
    </div>
    <p><input type="submit"></p>
</form>
<script>
    $('#the-form').on('submit', function() {
        $('.btn.active', '#the-form').each(function() {
            var input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", this.name);
            input.setAttribute("value", this.value);
            document.getElementById("the-form").appendChild(input);
        });
    });
</script>

注意:为了实现这一点,我必须为表单提供一个id,并为按钮提供唯一的名称(因为它们是buttons-checkbox而不是buttons-radio,请参阅文档)。

如果您想要buttons-group行为,请使用:

<div class="btn-group" data-toggle="buttons-radio">
    <button type="button" name="bb" value="b1" class="btn btn-primary">Left</button>
    <button type="button" name="bb" value="b2" class="btn btn-primary">Middle</button>
    <button type="button" name="bb" value="b3" class="btn btn-primary">Right</button>
</div>

.btn-group下的按钮没有提交,因为它们的类型不正确。您需要将type="button"更改为type="submit"。只有具有type="submit"的按钮才会提交父form(默认按钮类型为submit)。

<div class="btn-group" data-toggle="buttons-checkbox">
    <button type="submit" name="bb" value="b1" class="btn btn-primary">Left</button>
    <button type="submit" name="bb" value="b2" class="btn btn-primary">Middle</button>
    <button type="submit" name="bb" value="b3" class="btn btn-primary">Right</button>
</div>