Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn a button group in Bootstrap into a radio-style input to my form?

I have the following HTML that creates a radio button group using Bootstrap.

<div class="btn-group" data-toggle="buttons-radio">
  <button class="btn" type="button" name="rating" value="1">
    <img ...>
  </button>
  <button class="btn" type="button" name="rating" value="2">
    <img ...>
  </button>
  <button class="btn" type="button" name="rating" value="3">
    <img ...>
  </button>
  <button class="btn" type="button" name="rating" value="4">
    <img ...>
  </button>
</div>

<button class="btn" type="submit" name="submit">Submit</button>

Based on user selection, I want to send the variable in the form from the radio group named "rating" with the value assigned to whatever the selected button's value is. How would I do this in jQuery?

like image 662
ArKi Avatar asked Apr 23 '12 00:04

ArKi


1 Answers

$('button[name="rating"].active').val();

In plain English that selection reads as:

  • give me the value of
  • button elements
  • filter by the name attribute that has a value of rating (the group)
  • and the CSS class active (indicating it was selected)

Edit based on OP's new question in comments:

To capture the input from the button you will need to use custom script handlers. If your goal is to actually submit this with the form, I would actually suggest against it. Mostly because this is not what a user is expecting in a form. Just use a regular radio button input.

However if you do want to use this, you can do the following:

$('form').submit(function() {
    var rating = $('button[name="rating"].active').val();  

    // get the rest of the values
    // submit the form
});​

Here's an example with a regular input vs. the button and why you shouldn't use the button in a form: http://jsfiddle.net/TxgVe/1/

like image 200
Terry Avatar answered Sep 17 '22 14:09

Terry