I\'m using the new jquery mobile 1.0 alpha 1 release to build a mobile app and I need to be able to toggle the text of a button. Toggling the text works fine, but as soon a
For some reason I am not having an 'ui-btn-text' classed span the first time I want to change the button text. So I workaround it like this:
var button = $("#consumed");
var innerTextSpan = button.find(".ui-btn-text");
// not initialized - just change label
if (innerTextSpan.size() == 0) {
button.text(label);
// already initialized - find innerTextSpan and change its label
} else {
innerTextSpan.text(label);
}
In the new jquery mobile version there is an inner span tag within the button.
So you have not to change the text of the 'a' tag but to change the text of the inner span.
e.g.
$("#consumed .ui-btn-text").text("test");
For markup like
<button id="consumed">Mark Old</button>
$("#consumed").html("Mark New");
$("span > span", $("#consumed").parent()).html("Mark New");
I wrote a simple plugin to do this for either a link based button, or an <input type="button">
button. So if you have
<input type="button" id="start-button" val="Start"/>
or
<a href="#" data-role="button" id="start-button">Start</a>
Either way, you can change the displayed text with
$("#start-button").changeButtonText("Stop");
Here's the plugin:
(function($) {
/*
* Changes the displayed text for a jquery mobile button.
* Encapsulates the idiosyncracies of how jquery re-arranges the DOM
* to display a button for either an <a> link or <input type="button">
*/
$.fn.changeButtonText = function(newText) {
return this.each(function() {
$this = $(this);
if( $this.is('a') ) {
$('span.ui-btn-text',$this).text(newText);
return;
}
if( $this.is('input') ) {
$this.val(newText);
// go up the tree
var ctx = $this.closest('.ui-btn');
$('span.ui-btn-text',ctx).text(newText);
return;
}
});
};
})(jQuery);
... because sprinkling your code with dependencies on exactly how jQuery Mobile renders these buttons is not a good idea. Programming rule: if you gotta use a hack, isolate it to a well-documented, re-usable chunk of code.
For those interested in a easy solution, I created a plugin called Audero Text Changer.
When you create the button it adds some additional elements, some inner <span>
elements that look like this:
<a data-role="button" href="#" onclick="Podcast.consumed(); return false" id="consumed">
<span class="ui-btn-inner ui-btn-corner-all">
<span class="ui-btn-text">Mark Old</span>
</span>
</a>
To change the text, you'll want this selector:
$("#consumed .ui-btn-text").text("Mark New");