You cannot execute methods before initializing; tried to execute the method 'refresh'

Trying to change the value of a link-button when clicking on a menu item.

Sample 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 code snippet:

$('#selected').hide();

$("#menu li a").on('click',function(){
    $('#selected').html($(this).html()).slideDown().button("refresh");
});

The text updates as expected, but there is an issue with the button's CSS styling.

An error message is displayed:

Uncaught Error: cannot call methods on button prior to initialization; attempted to call method 'refresh'

What exactly needs to be initialized here? The page and button seem already set up, right?


Additional attempt using jQueryMobile initialization:

$(document).on("mobileinit", function() {

    $('#selected').hide();

    $("#menu li a").on('click',function(){
        $('#selected').html($(this).html()).slideDown().button("refresh");
    });

});

No more error messages are shown; however, the text still doesn't update properly :(

Answer №1

A common problem arises when there is a conflict between the jquery-ui and bootstrap-button plugins. To resolve this, make sure that the jquery-ui code is placed before bootstrap.js in your script load order.

Answer №2

Example in Action

To see this solution in action, check out the working example here: http://jsfiddle.net/Gajotres/BDmex/

Code Snippet :

<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>

Javascript:

$('#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();
});
  • Don't forget to include data-role="button" inside the button tag
  • If your button lacks text, make sure to structure it with 2 inner spans

Another Approach

For an alternate solution and more insights, refer to this informative ARTICLE, which includes a detailed description and a functional example.

Answer №3

Inspect the HTML structure of your #selected link element after jQuery Mobile has initialized it using a DOM inspector. The text is located within a span element with the class ui-btn-text. Therefore, when you use the .html() function to update the button's HTML, you end up erasing the formatting applied by jQuery Mobile.

To update the text without losing the formatting, target the descendant .ui-btn-text element of your button.

Replace this:

$('#selected').html($(this).html()).slideDown().button("refresh");

with this:

$('#selected').find(".ui-btn-text").html($(this).html()).slideDown();

For reference, here's an example of an initialized anchor tag button's HTML structure:

<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:

Answer №4

I encountered a similar issue and could not pinpoint the cause. However, I came up with a workaround based on the fact that a span with class 'ui-btn-text' is inserted into the button after initialization:

var selectedButton = $("#selected");
var innerTextSpan = selectedButton.find(".ui-btn-text");

// If the span is not initialized, just update the button text
if (innerTextSpan.size() == 0) {
    selectedButton.text(label);

// If the span is already initialized, locate it and update its text
} else {
    innerTextSpan.text(label);
}

Answer №5

Encountering a similar issue, I managed to resolve it by removing two concluding quotation marks from the html code. This led me to believe that there may be a flaw in the destination page's html structure.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating the Results of a Script into TinyMCE with the Help of

Recently, I developed a script for creating a basic table layout structure. To enhance its functionality, I decided to integrate AJAX with jQuery in order to input the output of the script into a TinyMCE textarea. The PHP script itself works seamlessly whe ...

Trouble with CSS and jQuery: Is document.height accurately reported? Why won't the div stretch vertically?

Surprisingly, I haven't been able to find anyone else facing this issue. O_o Check out the code on Pastebin here The code is causing a gap between the end of #main and the end of the actual page on IE, Chrome, and Safari, but not on Firefox. The ba ...

An uncomplicated vessel design

Having experience in mobile programming, I am accustomed to creating a parent hidden view and positioning subviews inside it. Now, I am trying to replicate the same functionality using HTML/CSS/Bootstrap. Let's say I have already laid out a cover bac ...

The 'OR' statement in jQuery (||) is not functioning correctly within an if condition

I am facing an issue with a dropdown menu and colorizing its options based on their values. Here is the scenario: If the Option value is "f1" OR "f2", then the dropdown color should be "blue". Otherwise, it should be "red". Below is the code snippet: &l ...

Move the last specified elements to the beginning of the array

I have an array let colorsArr = ["red", "green", "purple", "pink", "black"]; Is there a way to retrieve a specific number of elements from the END and move them to the BEGINNING of the array? Desired result: example 1: //move last 3 elements let expec ...

Encountering NullReferenceException with SharePoint 2007 HttpHandler when using SPContext.Current.Site/Web in conjunction with jQuery

I am working on developing a custom HttpHandler in SharePoint and encountered an issue while coding a simple example: http://pastebin.com/HXLjR2xT. Specifically, I am facing a NullReferenceException on line 35 or 36 when attempting to call my HttpHander pa ...

Displaying MySQL results in a vertical sequence

I've stored the data in my database as follows: Football ART-NR-1337 Price: 5$ Basketball ART-NR-1333 Price: 10$ Now, I am working on a .php file that displays the articles like this: Football Basketball ART-NR-1337 ART-NR-1333 Price: 5$ ...

NodeJS async/await not pausing for the completion of the previous request's response

function fetchData(input) { return new Promise((resolve, reject) => { $.post({ url: baseURL, data: input }).done(function (response) { resolve({ statusCode: 200, responseData: response }); ...

Displaying MongoIds in HTML output for the user

Currently, I am in the process of developing a web application that utilizes MongoDB as its database management system. One challenge I am facing is finding a way to accurately identify which object the user has selected from a list on the screen, and the ...

How to retrieve the name of a dynamically generated div using JavaScript?

My JavaScript .click() method isn't working with dynamically created divs. I have divs under the class name "class1" but the click method doesn't detect them. Here's my code: <link href="../../Content/Site.css" rel="stylesheet" type= ...

Tips on restricting users to only uploading images under 100 KB

Is it possible to create an input tag that allows for the uploading of multiple images? In my current implementation, I have a format limitation in the preview (triggered on change) which only allows JPEG and JPG files. How can I introduce another restric ...

Having trouble with your WordPress child theme's formatting?

Despite researching similar issues on stackoverflow and WP Codex, I have been unable to resolve my problem. This is the second child theme I have created, with the first one functioning perfectly. However, this new theme does not inherit the formatting fro ...

How can I automatically fill a form with data using PHP and jQuery?

function autoFillForm($formData) { //Format: $formData['css_selector'] = "value"; $html = "<script>\n$(document).ready(function(){\n"; foreach($formData as $selector => $value) { $html .= "$('$sele ...

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

As the text is being selected within a react-rnd, once the selection extends outside of the draggable component, the selected text will automatically adjust

I've encountered an issue with a draggable textarea created using react-rnd. The problem arises when I try to select text within the textarea, and accidentally move my cursor outside of the react-rnd component, causing the selection to change unexpect ...

Add a unique class to the <li> element in Angular 2 when it is clicked

Here is an example of a component I am working on: <li > <a (click)="status='today'" class="search-dropdown-tabs-active">Today</a> </li> <li> <a (click)="status='tomorrow'">Tomorrow</a> ...

The Twitter widget is not staying in sync with the rest of the page when scrolling on

Twitter provides a widget that is widely used by many people. Below is the code provided by Twitter: <script src="http://widgets.twimg.com/j/2/widget.js"></script> <script> new TWTR.Widget({ version: 2, type: 'profile', ...

The combination of $.post and $J = jQuery.noConflict() does not seem to be functioning correctly

I'm struggling with sending data from JavaScript to PHP using the $.post method, while also having conflicts with WordPress and using $J = jQuery.noConflict(). Here's what I have in my JavaScript: $J = jQuery.noConflict() x=1 $J.post('/the ...

Encountering issues with the fancy box feature on Internet Explorer

Hey, I'm having an issue with my fancy box and jQuery menu bar on my website. Everything is working fine in Chrome, but it's not functioning properly in IE. I tried adding the following code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Stric ...