I'm a newbie to Javascript and from what I've read I assume there is a much better way to my approach, but here it goes.
I have a form with onclick such that when a clear image is clicked on in a table cell, the background pic of the cell changes (showing that it has been selected, or unselected if clicked again). That all works, now I want to define some variable so that when the form's Submit button is pressed, a form variable is passed showing whether or not the user selected that option.
The functional javascript I found on the internet:
var curPic1 = 0; window.onload=function() { document.getElementById('clear-kayangan').onclick=function() { curPic1 = (curPic1 == 0)? 1 : 0; document.getElementById('td_kayangan').style.backgroundImage = (curPic1 == 1)? 'url("pics/map-kayangan-lake-selected.png")' : 'url("pics/map-kayangan-lake.png")'; } }
My plan was to write an IF statement stating if curPic1 == 1
(the background image chosen shows that the user has selected), I would create a Global variable which I could then pass on to php in the form:
$spot1 = "<script>document.write(spot1);</script>"; if ($spot1 == 1) echo "<input name='spot1' type='hidden' value='1' />";
For testing purposes I tried:
$spot1=$_POST['spot1']; if ($spot1=="1") echo "<b>This really works</b><br>";
and it works if I use If $spot1==0
, whereby at the top of my javascript function I tried the following:
spot1=0; var spot1=0;
and within the javascript function itself I tried:
spot1 = 1; window.spot1 = 1;
I haven't yet tried the IF statement because I'm just trying to test things if they work. I read that I was supposed to be able to establish a Global variable from within a function. I added the various options above one at a time. It works with spot=0
, so I assume the problem is that it is not being set as a Global variable within the function? Or perhaps there is a better approach to all this?
On Submit the hidden form variables will eventually be passed to another page and used there.