Do more with buttons: feedback and toggling

Bootstrap has a simple built-in method to automatically set a button to disabled and provide some feedback to the user. Click this button to see what I mean:

Neat, right? Here's how to do it:

  • Add the  data-loading-text  attribute to the button. The value is the text that gets displayed when the user clicks the button.
  • Add an onclick event to set the buttons state to loading.
The thing to watch out for is that the state has to be reset too after the process completes. One way to do that is to partial refresh the area that contains the button.

And here's the code:

<xp:button value="Get me a drink!" id="button2" styleClass="btn btn-warning" onclick="$(this).button('loading');">
  <xp:this.attrs>
    <xp:attr name="data-loading-text" value="Your drink is being served"></xp:attr>
  </xp:this.attrs>
  <i class="glyphicon glyphicon-glass " />
</xp:button>

(the live button actually also has a  simple server side script that waits for 2 seconds before it's finished...)

A simple toggle button

You can also use standard Bootstrap buttons to create toggle button:

Turn the light:

Or with a little styling:

Are you gonna use this?

All that's needed is this little code snippet. The  data-toggle="buttons-radio"  is the important part here: it tells Bootstrap to treat the buttons in the div as a group where you can only enable a single option. You can also set it to buttons-checkbox. Guess what that does...

(by the way: the script block is only needed if you want to change the color of the active button)

<div id="div1" class="btn-group span4" data-toggle="buttons-radio">
  <xp:button styleClass="btn btn-success active">On</xp:button>
  <xp:button styleClass="btn">Off</xp:button>
</div>
					
<xp:scriptBlock id="scriptBlock2">
  <xp:this.value>
    <![CDATA[$("#switch .btn").on("click", function() {
      $(this)
        .addClass("btn-success")
        .siblings()
          .removeClass("btn-success");
      });
    ]]>
  </xp:this.value>
</xp:scriptBlock>