+ 2

This problem is eating my head from a long time PLZ help!

The following code consists of a form that is calling a function on submitting. var 'x' is a global variable but it doesnot behave like one. the value of x should actually go on increasing but it doesnt.(it just outputs 1 all the time) ps:i know things are missing from the form tag but it doesnt matter in this case. <html> <head> <script> var x=0; function myform(){ x++; alert(x); } </script> </head> <body> <form name="form" method="post" onsubmit="return myform()"> <input /> <input type="submit"/> </form> </body> </html>

3rd Jul 2017, 5:25 PM
Calden Rodrigues
Calden Rodrigues - avatar
6 Respostas
+ 3
Your code is almost done! the problem was that you used the method="post" which will eventually hide all data. just change the <form method="post"> into <form method="get"> or remove entirely, the method attribute. then your code will run as you expected.
3rd Jul 2017, 7:27 PM
Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel - avatar
+ 1
Add this.event.preventDefault() in myform function
3rd Jul 2017, 5:31 PM
Calviղ
Calviղ - avatar
+ 1
yes @vijay saini
3rd Jul 2017, 5:55 PM
Calden Rodrigues
Calden Rodrigues - avatar
0
x=0 at the beginning, then, x++. x=1. and finally alert(x) x=1 so it displays 1
3rd Jul 2017, 5:31 PM
Jojo
0
OOw I've just understood, what you want ! Each time the page will be loaded, x will be initialize to 0. So that's normal it always displays 1
3rd Jul 2017, 5:34 PM
Jojo
0
@jojo The thing is I am not loading the page again and again, I am just going on pressing the submit button and still it shows 1 all the time. will try this.event.preventDefault() and see. but would like some explanation on it.
3rd Jul 2017, 5:46 PM
Calden Rodrigues
Calden Rodrigues - avatar