简体   繁体   中英

Dynamically change and check variable in javascript

I have the following code:

JS:

var flag = 0;
funct(){//makes changes on css
flag=0;}

HTML:

<form onsubmit="if(flag==1)return funct()">

PHP:

if(somethingIsOK){
    echo "<script>flag=1;</script>"; //should use new css which comes with funct()
}else{//do something else with keeping the existing css}

I want this structure, but I could not use the variable flag like I wanted to. I have tried making flag static but it did not work.

Use the hidden field to set/unset flag

<input type="hidden" name="flag" id="flag" value="1" />

javascript

var flag = document.getElementById('flag').value;
funct(){//makes changes on css
document.getElementById('flag').value=0;
}

I don't like the way you do it, but the answer is to delete var before flag to make it global:

flag = 0;

proof

EDIT

  1. if you want to prevent form submit your funct() must return false;
  2. maybe you try

     if(somethingIsOK){ echo "<script type="text/javascript">flag=1;</script>"; }else{ echo "<script type="text/javascript">flag=0;</script>"; } 

and again: it's a very-very bad idea to mix php and JS like that

You can't easily use the same variable in both PHP and JS. What you can do however is make a <input type="hidden"> with the name flag and the value of the variable and then read it in both PHP and JS.

Its bad idea to use constructions like this, but if you realy want use some global variable you can assign it to window object property, ie:

window.flag = 0;

And use this variable(window.flag) everywhere you need it.

var flag = 0;
funct(){//makes changes on css
flag=0;}

try

var flag = 0;
function funct(){  // <<<<< function
//makes changes on css
flag=0;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM