I’m in the process of writing a mobile app using PhoneGap and jQuery Mobile.
In retrospect, it may have been more trouble than it’s worth, with hours and hours spent chasing down undocumented features and bugs, but overall I don’t regret mucking around with it, and I do think it’s pretty cool.
Because mobile interfaces are small, I wanted to give the user the option to add additional fields without cluttering up the screen real estate for those that didn’t. So, that meant I had to present one field, and then give the user the controls (a plus symbol, an “add more fields” button, etc) to add more. If they hit the add button too many times by accident, I wanted to give them a way to remove extra fields as well. And finally, I wanted to limit the number of fields they could add and provide them with some helpful feedback by changing the text on the (disabled) “add” button once they’ve hit the limit.
This is a modification on Charlie Griefer’s post on how to add and remove fields dynamically using jQuery.
That tutorial is great for straight jQuery, but it doesn’t work for jQuery Mobile, since jQuery Mobile does all kinds of kooky styling in order to give you the easy mobile-esque design.
The problem was that standard jQuery disabling/class manipulations wasn’t working because JQM does some DOM element rewriting to add all of the sexy styles, so it needs a JQM-friendly way to say that a button is disabled. The JQM docs say that “All jQuery Mobile widgets can be disabled in the markup by adding the standard disabled attribute to the element, just like you would with native controls.” With all due respect, I have not found this to be true.
Things that didn’t work:
What finally DID work:
- $(‘#btnAdd’ ).attr(‘disabled’, ‘disabled’).button(‘disable’);
I also added in the ability to change the text on the add button once the limit has been reached.
This script requires jQuery Mobile and jQuery, of course. This version was tested with JQM 1.0, and jQuery 1.6.4. In my implementation, I am also using PhoneGap 1.2.0, but that shouldn’t matter here.
The code is below, and it’s up on Github if you’ like to fork it, or you can clone it here:
git clone git://gist.github.com/1925906.git gist-1925906