I have the following very simple code snippet which is loaded from a separate file into one jQuery Mobile page in a multi-page site that I am building:
$(document).ready(function(){
$('select[name="state_choice"]').change(function(){
var thisState = $(this).val();
var indexState = '#' + thisState;
$('.state').hide();
$(indexState).show();
});
})
It was working but now it only works when I reload the page. I was examining the page load with Firebug and it was not consistently loading the jQuery file because this link was not showing up until reload.
<script src="inc/jquery/belmont.custom.js"></script>
Typically the console will show when a new page is called in jQuery mobile but I did find that this particular page did not always show up in the console log when a link to it was clicked. I have tested on a desktop simulator (Dashcode’s iOS Simulator), in desktop browsers (FF and Safari) and on my iPhone all with the same results.
Has anyone ever seen this behavior? How can I make sure that this works consistently?
EDIT: I have changed the code to use bind as follows:
$(document).bind('pageinit', function(){
$('select[name="state_choice"]').change(function(){
var thisState = $(this).val();
var indexState = '#' + thisState;
$('.state').hide();
$(indexState).show();
});
})
I have added console.log(indexState) to the function and this does not fire consistently either.
And I actually mis-spoke earlier – this is a mobile site consisting of single pages. Do I have to load the jQuery custom function script into every page? Or can I just load it into the one in question?
Here is how I got it sorted out. Since jQM loads each subsequent page with AJAX you need to treat interactions like this like any other dynamically loaded element. Changing
bind()toon()(I am using jQuery 1.7+) gets everything working like it should: