views:

22

answers:

2

Hello, I'm developing the ajax search script. it's the simple code, I get javascript error. I can't see the error! And I don't understand why I have an error here:

<script>
  var keywords = document.advanced_search.keywords.value;
  alert(keywords);
</script>
<form name="advanced_search">
<input name="keywords" type="text" value="213123">
</form>

JavaScript error : 'document.advanced_search.keywords', null or not the object.

+1  A: 

Try to move script block after the form. Your script is run in time when form doesnt have to exist yet.

pepiino
@question: The only way to put the script there would be to wrap it in a function called after the DOM has been loaded. `window.onload` does it, but it waits for all images first, which is pretty late. Various JavaScript libraries -- [Prototype](http://prototypejs.org), [jQuery](http://jquery.com), [Closure](http://code.google.com/closure/library), or [any of several others](http://en.wikipedia.org/wiki/List_of_JavaScript_libraries) -- provide ways of doing it after DOM load but earlier than `window.onload`. But just putting it at the end of your page is fine, doesn't have to be in `head`.
T.J. Crowder
1) Script doesn't have to be in head. It's commonly suggested to place it at end of body (this suggestion comes from speed optimization and from the way browser processes scripts)2) You have to run your script after the browser initialize the page... one way is to attach it to the window.onload or you can use for example jquery: $(document).ready(function() {...your code...});Almost every JS framework has simillar method.
pepiino
@ALL:I know javascript frameworks and Javascript Libraries. Thanks for answers. I tried as under , that works.<head><script>function demo() { var keywords = document.advanced_search.keywords.value; alert(keywords);}</script></head><body><form name="advanced_search"><input id="keywords" name="keywords" type="text" value="213123"></form><script>demo();</script>
question_about_the_problem
A: 

In order to access DOM elements from JavaScript you should use document.getElementById("keywords").

<script>
  var keywords = document.getElementById("keywords");
  alert(keywords);
</script>
<form name="advanced_search">
<input id="keywords" name="keywords" type="text" value="213123">
</form>

And this have to be called of course after the DOM is loaded. So:

<script>
window.onload = function(){
     var keywords = document.getElementById("keywords");
      alert(keywords);
}
</script>
Balint Pato
Thanks for your answer, but i know this informations. I just want to understand why there is an javascript error. Now I understand:@peppino: "Try to move script block after the form. Your script is run in time when form doesnt have to exist yet."Thanks.
question_about_the_problem