douwen5951 2017-07-25 17:56
浏览 33

onclick变量未传递给表单

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:

int spot1;
spot1=0;
var spot1=0;

and within the javascript function itself I tried:

int spot1 = 1;
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.

  • 写回答

2条回答 默认 最新

  • dongwei2983 2017-07-25 18:11
    关注

    Declare hidden variable in the form, and set it's value to 0 or 1 in onclick fuction of image. When form is submitted, this value will also be passed to server

    评论

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像