Variable setting not going through to form element
I have a global variable called 'name', when a user clicks on a button a text boxes content is queried and 'name' is set to the contents then the name gets printed in a different jquery page.
My problem is name is never printed as the name it was set to, it's always printed as what it was initially set to instead.
Here's my callback function:
<script type="text/javascript">
$("#finalize").click(function(e)
{
g_name = "BLAH";
return true;
});
</script>
For simplicity I've set the name to just be 'BLAH' on the click.
g_name is declared globally (i.e. outside the function scope).
In the other jquery page I have:
document.write('<label for="testname">Name:</label>');
document.write('<input type="text" name="testname" id="testname" value="');
document.write(g_name)
document.write('"/>');
And g_name is always shown as something else, whatever g_name was initially initilized to.
The button whose click callback sets the global variable also transitions the pages if that makes a difference...
edit:
Ok I've figured out what was wrong, the global variable was being written down before it was set. Now I'm trying to do this:
<script type="text/javascript">
$('#confirmscreen').bind('pageshow',function()
{
document.write('<label for="testname">Name:</label>');
document.write('<input type="text" name="testname" id="testname" value="');
document.write(g_name);
document.write('"/>');
开发者_StackOverflow社区 document.write(g_phonenumber);
});
</script>
However jquery doesn't seem to like using document.write on the 'pageshow' event, is there a way I can make this work, that is to say, write out g_name WHEN the page shows and not when the website is loaded up?
Instead of using document.write use the javascript method document.createElement() and use the setAttribute() method to assign the values and attributes to the created element.
Hope this helps you.
If that button is causing the page location to change then your global variable will be reset and not available on the second page if that makes sense. In javascript global variables are per window, if window location changes, new set of global variables.
精彩评论