Search code examples
javascriptjqueryjquery-mobilejquery-events

How to bind to submit event in jQuery Mobile pages


Tried to bind submit event (or click or whatever) to an element within a jQuery mobile page. What I wanted to do is get the value from an input within an form element within a jQuery page and store it in cookies/localStorage. Every time I come back to this page I want to restore the input field.

Currently I ended up in using this script:

    $('.pageClassSelector').live('pageinit', function (e) {

        $('.classSelector').submit(function () {
            var q = $('.inputClassSelector').val();
            // store to localStorage ...
        });

    // load from localStorage ...
    $('.q').val(lastSearchString);

    });

This approach is documented there http://jquerymobile.com/test/docs/api/events.html

Since it seems possible that identical pages are hold in the DOM, ID selectors are not quite useful. My problem now is that everytime I navigate to this page the submit event is bound again and thus results in storing DIFFERENT (!) values. The submit event seems to be fired multiple times and much more interesting with the value before last.

Am I doing anything completly wrong? Any hints how to do scripting in jquery mobile properly?

TRY1:

I placed now the submit event binding within the pagebeforeshow event like so:

$('#PageId').on('pagebeforeshow', function (e) {
    $('.classSelector').on('submit', function () {
            var q = $('.q').val();
            alert('stored: ' + q);         
    }
    $('.q').val(lastSearchString);
}

But the value going to be stored is still the value before last, when I was navigating the page before. The first time it works as it should.

TRY2:

This is what I have now and it looks like it does that what I want. I select now the current page and select only the form which is a child of this page. Is this good practice?

$('div:jqmData(id="PageId")').on('pagebeforeshow', function (e) {

     $(this).find('#form').on('submit', function () {
        var q = $(this).find('#input').val();
        localStorage.setItem("key", q);
        return true;
    });

    lastSearchString = localStorage.getItem("key");
    $(this).find('#input').val(lastSearchString);        
});

Solution

  • Your requirement to load from local storage and store on the page needs to be done by binding to the pagebeforeshow event (look at the section "Page transition events") and not the pageinit event like you are currently doing.

    $('.pageClassSelector').on('pagebeforeshow', function (e) {
        // load from localStorage ...
        $('.q').val(lastSearchString);
    });
    

    Furthermore generally each page element (where you have data-role='page') should have a unique ID so you can use that instead of the CSS selector.