0

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

I have this script:

<script>
var dataoriginale = document.getElementById("savedataoriginale").value;
</script>

and this text field:

<input name="savedataoriginale" id="savedataoriginale" type="text" value="testtest">

but when I try to print the javascript var

<script>document.write(dataoriginale)</script>

I get undefined.

Why? How can I fix that?

Community
  • 1
  • 1
Perocat
  • 1,481
  • 7
  • 25
  • 48
  • Hard to tell because it works fine here: http://jsfiddle.net/fkling/GLpep/. Maybe you are trying to access the element before it exists. In that case, have a look at http://stackoverflow.com/q/14028959/218196. Otherwise you have to provide a more complete example. – Felix Kling Jan 28 '13 at 13:23
  • sorry, I posted the first javascript over the input... Usually we declare first the variable and then we work with it, not? – Perocat Jan 28 '13 at 13:26
  • Yes, but you cannot access the DOM element before it exists. HTML is parsed from top to bottom. – Felix Kling Jan 28 '13 at 13:30

2 Answers2

3

it's cause you have 2 conflict js session before you get the value from the input

here is work option

<input name="savedataoriginale" id="savedataoriginale" type="text" value="testtest">
<script>
var dataoriginale = document.getElementById("savedataoriginale").value;
document.write(dataoriginale);
</script>
g.e.manor
  • 526
  • 6
  • 12
2

Most probably because the <script> is executed before the <input>. It happens because document.getElementById("savedataoriginale").value returns undefined when the DOM is not parsed.

To solve this, put your <script> tag after the <input> and make sure it doesn't run until the DOM is parsed. You may as well use the DOMContentLoaded event like this:

document.addEventListener("DOMContentLoaded", function(){
  var dataoriginale = document.getElementById("savedataoriginale").value;
  alert( dataoriginale );
},false);

More info:

PS. you don't need to have both id and name attributes on your <input> element. Name is deprecated. ID is enough.

Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104
  • `name` is deprecated? Since when? Each form element needs a name to be "successful": http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.2. – Felix Kling Jan 28 '13 at 13:31
  • Yeah, I'm not sure if he was actually trying to submit a
    since there wasn't any
    in the code snippet. But yes, if it's going to be submitted with the popular goold old "action" and Submit button it is better to provide name.
    – AlexStack Jan 28 '13 at 13:38