Chris Pilie
Chris Pilie

Reputation: 451

Pass variable to dialog variable in jQuery Mobile

I have a button that opens up a dialog containing another html file. What I would like to be able to do is pass a variable to the dialog. This is what I have.

var html = ""; 
var PLAN_ID = '1234';
html += "<div>"
html += '<a href="formFinal.html?Planid=' + PLAN_ID +'" data-rel="dialog" data role="button">Final</a>'
html += "</div>"

The PLAN_ID variable is the one that I wish to push to the formFinal.html. I can populate a hidden text input on the dialog with the following code.

$(document).on('pageshow', '#FinalPostPage', function(e) {
  var page = $(this);
  var query = page.data("url").split("?")[1];
  var planid = query.split("=")[1];
  $("input[name=Title]",this).val(planid);    
})

I can use this but the variable doesn't populate until after the formFinal.html page loads it seems. I need the variable to be used while the page develops. Hope this makes sense.

Upvotes: 1

Views: 2215

Answers (1)

krishwader
krishwader

Reputation: 11371

You could use localStorage to transfer data from this page to the other page.

When you're creating the button, add the PLAN_ID variable as a data-* attribute to the a and also create an id/class for it :

var html = ""; 
var PLAN_ID = '1234';
html += "<div>"
html += '<a href="formFinal.html" id="dialog-send" data-planid="' + PLAN_ID + '" data-rel="dialog" data role="button">Final</a>'
html += "</div>"

Write a click event for the button click :

$(document).on("click", '#dialog-send' ,function(e) {
   //prevent default action. we dont want it to redirect. Just yet. 
   e.preventDefault();
   //set item in localStorage.
   localStorage["plan_id"] = $(this).data("planid");
   //then use changePage to redirect 
   $.mobile.changePage(this.href, {transition: 'pop', role: 'dialog'});     
});

In your pageshow event,

$(document).on('pageshow', '#FinalPostPage', function(e) {
  var page = $(this);
  //var query = page.data("url").split("?")[1];
  //get plan id from localStorage 
  var planid = localStorage["plan_id"];
  $("input[name=Title]",this).val(planid);    
});

Hope this helps.

Upvotes: 5

Related Questions