lovespring
lovespring

Reputation: 19589

How to change jquery mobile button text

jQuery mobile will insert a lots of element after the elme be enhanced to a Widget.

for example, "a" will be inset two span elem after the "a" be enhanced to a button. so, how to properly modify the a's innerText after the "a" be enhanced to a button?

Upvotes: 1

Views: 1991

Answers (1)

Gajotres
Gajotres

Reputation: 57309

First official method don't exist so it must be done manually.

There are two common ways:

Classic solution:

    $(document).on('pagebeforeshow', '#index', function(){       
        $('#custom-btn span span').text('This is a new text');
    });

Live example: http://jsfiddle.net/Gajotres/EjVfz/

This solution expects nothings gonna change with future button implementations and everything will stay the same.

Cautious solution:

    $(document).on('pagebeforeshow', '#index', function(){       
        $('#custom-btn').find('.ui-btn-text').text('This is a new text');
    });

Live example: http://jsfiddle.net/Gajotres/QHg3w/

This solution is a safe solution, no matter which button example is used (a, button, input), button text will always be inside a .ui-btn-text class.

EDIT :

Change Button plugin

$(document).on('pagebeforeshow', '#index', function(){       
    $('#custom-btn').changeButtonText('This is a new text');
});

(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);

Live example: http://jsfiddle.net/Gajotres/mwB22/

Solution/plugin location: https://stackoverflow.com/a/7279843/1848600

Upvotes: 1

Related Questions