jQWidgets Forums
jQuery UI Widgets › Forums › General Discussions › javascript change global variable value within a function
Tagged: JavaScript
This topic contains 7 replies, has 2 voices, and was last updated by Dimitar 12 years, 3 months ago.
-
Author
-
hello
i want to change the global variable value within a function
say that i declared x with value of 20 and i have changed it in a function to 30 the problem is that when i alert the value of x from outside the function the value is still 20 not 30
may you help me solve that please
thank you
okasha
Hello okasha,
Please check out the question page Global Variable JavaScript (Changing Value) at Stack Overflow.
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/i have the following code but it still not working
$(document).ready(function () {
window.source123=20;$(‘#page_code_level’).bind(‘change’, function (event)
{
window.source123 = 30;}
alert(window.source123);
});
it still output 20 not 30
may you tell me where is the problem
Hi okasha,
Here is a revised version of your example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head> <title></title> <script type="text/javascript" src="../scripts/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(document).ready(function () { window.source123 = 20; $('#button').click(function (event) { window.source123 = 30; alert("Updated value: " + window.source123); }); alert("Initial value: " + window.source123); }); </script></head><body> <button id="button"> Change value</button></body></html>
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/hello Mr Dimitar
according to the provided code alert(“Initial value: ” + window.source123); will output 20 i want it to output the updated value
may you tell me how to fix iti am sorry for disturbance
okashaHi okasha,
The value is updated after the button is clicked (or any event you like). You may remove the alert of the initial value and show only the updated one.
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/the problem is that i want to use the updated value outside the function
Hi okasha,
After the button is clicked, the value is updated and you can use it outside the function. The alert, however, happens before the button click and that is why it still shows the old value.
Best Regards,
DimitarjQWidgets team
http://www.jqwidgets.com/ -
AuthorPosts
You must be logged in to reply to this topic.