1

Possible Duplicate:
Why does jQuery or a DOM method such as `getElementByID` not find the element?

Before the HTML tag I run some php code. During this I need to include some javascript lines like

..php code...
..javascript code...
..php code..
<html>
<head>
</head>
<body>
<input type="file" name="file" id="file">
</body>
</html>

In the javascript code I want to hide the file element.

This doesn't do anything:

..php code
?>
<SCRIPT LANGUAGE="JavaScript">
 document.getElementById('file').style.display = 'none';
</script>
<?php

...php code

If I put an alert there, it is displayed.

If I put that line into a function in the <head></head> block and call it from e.g. an onClick event of a button, the file element becomes hidden, so the line is fine. Maybe document.getLementByID is invalid outside the html tag? Or the problem is maybe that the page is not loaded yet so there is no element with that id? If this is the case, what can I do?

SOLUTION

I added a variable in the php code as $int = 1; (and $int = 0; somewhere else, but still before the page is loaded). Then in the <head></head> block:

window.onload = selectChoose;
function selectChoose() 
{
    if (<?php echo $int ?> == 0) {
        showChoose();
    }
    else {
        hideChoose();
    }
}

function showChoose() 
{
    document.getElementById('file').style.display = 'inline';
}

function hideChoose() 
{
    document.getElementById('file').style.display = 'none';
}
Community
  • 1
  • 1
erdomester
  • 11,491
  • 31
  • 126
  • 226
  • Is your javascript located outisde of the tags? It should be located there. – Ryan Beaulieu Jan 02 '13 at 20:34
  • @RyanBeaulieu Script tags don't have to reside in the head - in fact, for performance purposes, you used to want to put them as the last tag within your body. – Snuffleupagus Jan 02 '13 at 20:35
  • @snuffleupagus I am aware that script tags don't have to be in the head section. I guess I chose poor wording. I meant in regards to the code he had posted with the javascript being called outside the HTML. I meant he should put the javascript in the head section to see if it changed his outcome. – Ryan Beaulieu Jan 02 '13 at 20:39
  • @Ryan: it won't change the outcome, because there's no deferral (binding to an `onload`/`load` event); so the element *still* won't exist at the point at which the JavaScript is run. – David says reinstate Monica Jan 02 '13 at 20:42

2 Answers2

2

It is as you said, it just hasn't loaded yet.

JavaScript that affects a particular element must either be deferred (window.onload, on an event handler, etc) or else placed after the element it is trying to modify.

Niet the Dark Absol
  • 301,028
  • 70
  • 427
  • 540
2

Window onload will sort this out for you. Like so:

window.onload = function(){
     document.getElementById('file').style.display = 'none';
    }

This means once the entire site is loaded then it will perform the style.display command :)

Sir
  • 7,735
  • 12
  • 72
  • 138