简体   繁体   中英

javascript if condition not executing all commands

I'm having one little iritating problem. I have simple if condition in javascript code. It goes something like this:

if (istinito) 
{  
   alert ('123');
   document.getElementById('obavestavanje').value="Pobedi "+ime_igraca+"!!!"; 
   kraj=true;
}

Alert apears when istinito=true, but element with id="obavestenje" never get its value, and variable kraj never is set to true. Variable kraj is global variable, and there are no conflicts with other parts of the JS code. Any ideas why code stops after alert?

First advice i could give you: Use more console logging for debugging. Almost any modern browser got a console to debug and other things.

if (istinito) {
    console.log("i am here");    
}

from that same console you can also execute commands. Those dom manipulations are easily done from the console. just run them and see if it works.

the code:

document.getElementById('obavestavanje').value = "some value" 

looks ok. nothing wrong with it. i guess you don't have an element with id "obavestavanje" ?

Looks like document.getElementById('obavestavanje') is returning null. You are trying to de-reference the null reference by using document.getElementById('obavestavanje') .value which results in null pointer exception. If you look into the console, you should see some exception being raised. It is always a good idea to check if the document.getElementById() is returning a valid object before trying to dereference it.

eg

if (istinito) 
{  
   alert ('123');
   element = document.getElementById('obavestavanje')
   if(element){
      element.value="Pobedi "+ime_igraca+"!!!"; 
   }
   kraj=true;
}

Looks like your code is okay. And you are sure you have an element by id 'obavestavanje'. Could you please tell what element is it? Is it a button, textbox or someting like that?

Also the String in the "Pobedi "+ ime_igraca +"!!!" , what is 'ime_igraca'? Is it a variable and if it is have you defined this variable somewhere?

Or did you mean to give the value "Pobedi ime_igraca !!!" ??

Thanks Ranis MK

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