Reputation: 53876
I'm attempting to pass data between two pages.
Here is what I have so far : http://jsfiddle.net/8JXTT/49/
So im setting an attribute on the second page using : $("#secondpage").attr("val", "test value");
And to access this attribute I use : var val1= $(this).attr('val');
But for each 'Link Button' the value should be different.
In this fiddle I'm setting the attribute on the page itself when I should be setting it on the button?
How can I amend the code to pass a unique value associated with each button so that when the button is pressed the value is accessible on the subsequent page.
Fiddle code:
HTML
<div data-role="page" id="firstpage">
<div data-role="header">
<h1>First Page</h1>
</div>
<div data-role="content" id="links"></div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
<div data-role="page" id="secondpage">
<div data-role="header"> <a href='#' class='ui-btn-left' data-icon='arrow-l' onclick="history.back(); return false">Back</a>
<h1>Bar</h1>
</div>
<div id="pagecontent" data-role="content"></div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
JS
$(document).ready(function () {
for (var i = 0; i < 4; i++) {
var button = '<a data-role="button" href="#secondpage" data-theme="c" class="ui-btn ui-btn-corner-all ui-shadow ui-btn-up-c"><span class="ui-btn-inner ui-btn-corner-all"><span class="ui-btn-text">Link Button</span></span></a>';
$('#links').append(button);
$("#secondpage").attr("val", "test value");
}
$('#secondpage').live('pageshow', function () {
var val1 = $(this).attr('val');
$("#pagecontent").html(val1);
console.log('val is ' + val1);
});
});
Upvotes: 0
Views: 905
Reputation: 6911
I see several problems with your code:
val
directly while creating buttons, instead of making buttons set the value once clicked.$.data
to set datai
.To fix this, you need to 1. Bind a click event to new buttons that will set data of the page 2. Create a method to create a button which will be out of scope of your loop, and call it from the loop
Take a look at changed code, it should work http://jsfiddle.net/azZVk/12/ Also, it would be beneficial for you to know a little bit about closures. Take a look at this question for example: JavaScript closure inside loops – simple practical example
Upvotes: 1