5

How do I get the "state" of buttons which have been pressed in bootstrap?

I.e. I am using this code, which makes buttons 'toggle' like a checkbox:

<div class="btn-group" data-toggle="buttons-checkbox">
  <button type="button" class="btn btn-primary">Left</button>
  <button type="button" class="btn btn-primary">Middle</button>
  <button type="button" class="btn btn-primary">Right</button>
</div>

Which is from the bootstrap manual here.

But which I then click a submit button - there is no data contained in the $_POST. How do I know which button(s) have been selected?

I have tried adding 'value="1" name="1"' etc aswell to the buttons - but still nothing.

Edit: Here is the full solution, which I was able to create using the help from Felix below.

<form method="post" action="" id="mform" class="form-horizontal">
 <div class="btn-group" data-toggle="buttons-checkbox">
   <button type="button" name="left"   value="1" class="btn btn-primary">Left</button>
   <button type="button" name="middle" value="1" class="btn btn-primary">Middle</button>
   <button type="button" name="right"  value="1" class="btn btn-primary">Right</button>
 </div>
 <button type="submit" class="btn">Submit</button>
</form>

<script>
    $('#mform').submit(function() {
        $('#mform .btn.active').each(function() {
             var input = document.createElement("input");
             input.setAttribute("type", "hidden");
             input.setAttribute("name", this.name);
             input.setAttribute("value", this.value);
             document.getElementById("mform").appendChild(input);
         });
    });
 </script>
Laurence
  • 58,936
  • 21
  • 171
  • 212

1 Answers1

15

Buttons that are "selected" will have the active class attached to them. You can then use jQuery to only select those buttons. Since buttons are form elements, they can have name and value attributes and it's probably best to make use of those.

Example:

var data = {};

$('#myButtonGroup .btn.active').each(function() {
    data[this.name] = this.value;
});

To send the data to the server, you'd could use Ajax and set the data manually / merge it with other form data (if it exists).

You could also try to mirror the values into hidden form elements on submit if you want to use "traditional" form submission (see Change form values after submit button pressed).

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143