Tag Archives: bootstrap buttons

Disable a dynamically created Bootstrap button onClick

There might be times when you need to produce a dynamic list of things that you don’t want to happen twice, like updating the status of something, but in particular only wanting to act as a single use event on that line.  You can use jQuery to send a post request to perform the action, but it’s handy to be able to disable the button as well.  Doing so will guarantee the end user won’t be able to click again before the page/div/section refreshes,  even if you do update those above in the background.

If you have a button producing loop like this:

while([something happens to produce $row(for example)]){
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>
  <button class="btn btn-default btn-xs" id="dynamicBtn'.$row['id'].'" onClick="buttonFunction(this.id)>Disable Me</button>

Ignore the weird formatting on this thin blog page.

onClick calls a function and takes the ID value of the row to send to the said JavaScript method.  This, in turn, can then be used to disable (or anything else you need it to) the buttons on that line.  It’s quite generic actually and can be tailored for many different uses if you need it to do specific things to anything with the ID you are sending.

The JavaScript looks like this:

function buttonFunction(rowID) {
  $('#dynamicBtn'+rowID).prop("disabled", true);
  // Then do anything you need to do in the background if required

If the “do something in the background” is performing an AJAX request, you can make part of the “success” attribute re-enabling the button and giving an appropriate error message if something goes wrong.

You could also do this backwards and make disabling the button part of the AJAX success, but it leaves open the option of clicking several times if the request takes a few seconds to process.

It’s not good practice to be using jQuery lower than version 1.6 at the point of writing this, however, if you do, then switch out the newer “prop” method for “attr” to achieve the same thing.

Share this post:
read more