user2586173
user2586173

Reputation: 107

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.

Upvotes: 0

Views: 393

Answers (5)

JOE LEE
JOE LEE

Reputation: 1058

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

try

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

Upvotes: 0

coder
coder

Reputation: 701

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;
}

Upvotes: 1

vladkras
vladkras

Reputation: 17227

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

Upvotes: 0

Matyunin
Matyunin

Reputation: 39

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, i.e.:

window.flag = 0;

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

Upvotes: 0

lazyCrab
lazyCrab

Reputation: 187

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.

Upvotes: 0

Related Questions