Refresh dynamic selectmenu

Refresh dynamic selectmenu

Desired behaviour
Enter a number on a page, click the next button, the next page is displayed with a dynamically generated selectmenu displaying options 1 - x (previously selected number).

Current setup:
The select menu is entered as html code:
  1.    <div data-role="fieldcontain" id="container">
  2.       <label for="selectmenu" class="select">Options:</label>
  3.       <select name="selectmenu" data-native-menu="false" multiple="true" id="selectmenu">
  4.       </select>
It is then dynamically populated in js:
  1. for (var x=1; x<=numberSelected; x++ ) {
  2. $('#selectmenu').append('<option value="'+x+'">'+x+'</option>');
  3. }
  4.  
The Problem:
This works well. The problem I have is when I go back a page and try to change the number of options to be displayed and the selectmenu is not refreshed.

Attempted solutions:
I have read in other posts that the way to fix this is to use:
$('#selectmenu').selectmenu('refresh', true);

but when I tried that I ran into the error:
"Uncaught cannot call methods on selectmenu prior to initialization; attempted to call method 'refresh'"

So then I tried using:
$('#selectmenu').selectmenu();
$('#selectmenu').selectmenu('refresh', true);

and I got an error regarding this.list[0] is undefined on line 165 of jquery-mobile.1.1.1

I also tried the solution of:
$('#container').empty();
then recreate the content and 
$('#container').trigger('create');

this didn't throw an error but it resulted in no selectmenu being displayed.


I would be extremely grateful if someone could help me with this.

Many thanks.