I'd like to update the value of a link-button by clicking on the item of a menu.
Html:
<div id="menu">
<ul data-role="listview" data-icon="false">
<li><a href="#">Value A</a></li>
<li><a href="#">Value B</a></li>
</ul>
</div>
<a href="#" id="selected" data-role="button"></a>
jQueryMobile:
$('#selected').hide();
$("#menu li a").on('click',function(){
$('#selected').html($(this).html()).slideDown().button("refresh");
});
Text update works fine, but button css is not properly updated.
I get the following error:
Uncaught Error: cannot call methods on button prior to initialization; attempted to call method 'refresh'
Which initialization are we talking about ? Page and button are already initialized, aren't they?
EDIT:
I also tried this :
$(document).on("mobileinit", function() {
$('#selected').hide();
$("#menu li a").on('click',function(){
$('#selected').html($(this).html()).slideDown().button("refresh");
});
});
No error message any more; but no text update :(
The issue is sometimes caused by jquery-ui and bootstrap-button plugins conflict. jquery-ui code should go before bootstrap.js, and that solves the problem.
Here's a working example: http://jsfiddle.net/Gajotres/BDmex/
HTML :
<div id="menu">
<ul data-role="listview" data-icon="false">
<li><a href="#">Value A</a></li>
<li><a href="#">Value B</a></li>
</ul>
</div>
<a href="#" id="selected" data-role="button"></a>
JS :
$('#selected').hide();
$("#menu li a").on('click',function(){
$('#selected').html('<span class="ui-btn-inner"><span class="ui-btn-text">' + $(this).html() + '</span></span>').slideDown();
});
There's another solution to this problem and it can be found in this ARTICLE + description and working example.
Take a look at the HTML structure of your #selected
link element after jQuery Mobile has initialized it (using a DOM inspector). The actual text is inside a span element with the ui-btn-text
class. So when you update the HTML of the button with the .html()
function, you're overwriting the HTML structure that jQuery Mobile created, thereby removing the formatting that jQuery Mobile added.
You can select the .ui-btn-text
element that is a descendant of your button to update the text without removing the formatting.
Change this:
$('#selected').html($(this).html()).slideDown().button("refresh");
to this:
$('#selected').find(".ui-btn-text").html($(this).html()).slideDown();
FYI, here is what an initialized anchor tag button's HTML looks like:
<a href="#" data-role="button" data-corners="true" data-shadow="true" data-iconshadow="true" data-wrapperels="span" data-theme="c" class="ui-btn ui-shadow ui-btn-corner-all ui-btn-up-c">
<span class="ui-btn-inner">
<span class="ui-btn-text">Anchor</span>
</span>
</a>
Source: http://view.jquerymobile.com/1.3.0/docs/widgets/buttons/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With