2

Consider the following very simple code excerpt:

(...)
<div id="myDiv"></div>

<script>
    function appendSomeJQueryMobileStuff() {
        $('#myDiv').append($('<select/>'));
    }

    appendSomeJQueryMobileStuff();

    $(document).on('pageinit', function() {
        appendSomeJQueryMobileStuff();
    });

</script>

(try it out @ https://jsfiddle.net/ca544oob/)

Why is only the first <select> displayed with jQuery, but the second one isn't formatted at all? The only difference between the two function calls that I see is the moment when it happens.

And how do I fix this?

phil294
  • 10,038
  • 8
  • 65
  • 98

1 Answers1

4

Using jQuery Mobile , select menu plugin is auto initialized on any page that contains a select menu, without any need for a data-role attribute in the markup.You can check detail from official documentation here. In your case, you are appending select on pageinit , So you need to initialize the select menu plugin manually by adding

$( "select" ).selectmenu();

after

 $('#myDiv').append($('<select/>'));

Your final working code will be like..

(...)
<div id="myDiv"></div>

<script>
    function appendSomeJQueryMobileStuff() {
        $('#myDiv').append($('<select/>'));

    }

    appendSomeJQueryMobileStuff();

    $(document).on('pageinit', function() {
        appendSomeJQueryMobileStuff();

    // Initialization of Select Menu Plugin
        $( "select" ).selectmenu();
    });

</script>

Hope it will work for you .

Salman Nazir
  • 2,759
  • 2
  • 28
  • 42
  • so any plugin will NEVER work on any element, if it is applied after page load? This means, for every new element, initializing the plugin for ALL elements on the whole page is needed?? isn't this a complete waste of resources? Can't one simply initialize the select menu plugin once in the head somewhere? – phil294 Nov 08 '15 at 18:44
  • for a single page , if you initialize the plugin in one place , you don't need to initialize it every time you append new select. As in Append statement , you are just implementing 'Select' , SO One time initializing is must . You can move '$( "select" ).selectmenu();' in 'pageinit' after function calling. – Salman Nazir Nov 08 '15 at 19:08
  • ok I see. however, calling `.selectmenu()` on the one select object only makes more sense to me. thanks! – phil294 Nov 10 '15 at 21:28
  • Yes use .selectmenu() for one select, It will work fine for you. – Salman Nazir Nov 11 '15 at 07:01