Dynamically changing jQuery Mobile Buttons

This post is more than 2 years old.

Filed in the "In case you need to know" department, jQuery Mobile provides a basic API that allows you to modify buttons. This is more useful for creating new buttons, but also has uses for existing buttons. Specifically, I was looking for a way to swap out the theme of a button in a form based on what had been entered. Here is a simple example of this API in action:

Most of the template is boilerplate jQuery Mobile code. Note though the two buttons in the content section. Both are set to have no theme. Now - look at the JavaScript code at the bottom. I've got a basic click handler (should be touch I suppose) that will iterate over all possible theme values, including no theme specified. The API allows you to tweak pretty much everything, but I'm not sure what else you would change on the fly. Icon perhaps. Anyway, on the off chance someone needs this, here is a demo of the code above.

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Don Vawter posted on 6/27/2012 at 7:54 PM

Not directly relevant to your post but related and may be helpful to others creating buttons dynamically with jqm.
I was having trouble adding the decorations to a dynamically created button.
The step I was missing was adding $("#mynewbutton").button() after emitting the html.

Comment 2 by sam posted on 3/22/2013 at 3:38 PM

Thanks for this post. I notice in your demo that the button you are clicking on (either one) does not get the theme change, except for theme 'e' (I have no idea why just 'e' works). I imagine this is because of the associated events that are repainting the button back to the default theme. It would be super if you could find a way to make it work! Thanks.

Comment 3 by Raymond Camden posted on 4/19/2013 at 1:10 AM

Hmpth. That is interesting. I believe .. oh... just try switching click to touchend. Let me know if that works.