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

后端 未结 5 2035
一向
一向 2021-02-04 11:31

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

5条回答
  •  猫巷女王i
    2021-02-04 11:53

    Good news!

    Bootstrap 3 now uses input type="radio" button groups!

    If you don't want to upgrade, however, see my answer below:


    I'm using the following jQuery:

    $('[data-toggle="buttons-radio"]').children(".btn").click(function(){
        var value = $(this).val();
        $(this).parent().next().val(value);
        $(this).parent().next().valid(); // Remove this if you're not using jQuery Validation
    });
    

    For this to work, all you need to do is ensure each button has a value and have an input (I prefer to use type="hidden" but type="text" is good for testing) after the btn-group div.

    I noticed that if you submit the form and then hit the back button, all form data will still be present, including the hidden inputs, but the buttons will not be active. To fix that, add this extra jQuery:

    $('[data-toggle="buttons-radio"]').each(function(){
        var that = $(this);
        var value = that.next().val();
        if(value != "") {
            that.children("button[value="+value+"]").addClass("active");
        }
    });
    

提交回复
热议问题