Search code examples
bootstrap-4bootstrap-studio

Using buttons to set form values (Bootstrap/Bootstrap Studio)


This is what my form looks like, essentially I want the user to click hazardous or non-hazardous and have it set a value (itemtype) to Haz or NonHaz Here are my problems:

  1. I'm not sure how or where to store the itemtype variable

  2. I'm not sure how to allow only one button to be selected (and I don't want to use radio buttons) HazNonHaz


Solution

  • What's your reason that you don't want to use radio buttons? because radio buttons are the best for your scenario. If it's because of its look, bootstrap has a button plugin you can use:https://getbootstrap.com/docs/4.1/components/buttons/#button-plugin

    HTML

    <div class="jumbotron jumbotron-fluid">
        <div class="container text-center">
            <h1>
                Is your item considered Hazardous?
            </h1>
            <p class="lead">
                This includes all liquids, batteries and lighters.
            </p>
            <div class="btn-group btn-group-toggle" data-toggle="buttons">
                <label class="btn btn-primary active">
                    <input type="radio" name="hazardous-item" value="true" checked />
                    Hazardous
                </label>
                <label class="btn btn-primary">
                    <input type="radio" name="hazardous-item" value="false" />
                    Non Hazardous
                </label>
            </div>
        </div>
    </div>
    

    See the name for the radio button control "hazardous-item". I don't know what server-side language you use but that name could easily come from a boolean variable. This is how and where you store the variable.

    With bootstrap button plugin, when you click any of the buttons, it updates the underneath radio buttons as if you're clicking the radio buttons.

    To test, you can put this javascript on your page:

    $(function(){
        $('input:radio[name="hazardous-item"]').change(function(){
            console.info($(this).val());
        });
    });
    

    You can F12 to go to your browser's developer tool to see the selected value.

    On form post-back

    When you submit the form back to the server, the selected value, which is a boolean, will get binded to the variable, i.e. hazardous-item=true or hazardous-item=false.

    Screenshot

    enter image description here

    jsfiddle: http://jsfiddle.net/aq9Laaew/230903/