0

I'm trying to display form inputs using javascript. so I used this JS code block

<html>
<head>
</head>  
<body>    
<script>
var text = document.form1.name.value;
function printText(){   
    document.write(text);
}
</script>
<form name=form1>
<input type="text" id="txt" name="name"   ><br><br>
<input type="button" value="Submit!" onClick="printText();" >
</form>
</body>
</html>

but above code is not working. its giving me to undifined output

but when I'm trying below code its working....

<html>
<head>
</head>  
<body> 
<script>
function printText(){   
var text = document.form1.name.value;
    document.write(text);
}
</script>
<form name=form1>
<input type="text" id="txt" name="name"   ><br><br>
<input type="button" value="Submit!" onClick="printText();" >
</form>
</body>
</html>

so my problem is why we cant use this var text = document.form1.name.value; statement outside of function?

Thanks.

Ganesh Rengarajan
  • 2,006
  • 13
  • 26

3 Answers3

0

You assign value to variable text on document load and at first it's empty. In second case you call function on some button click wich gets form value and prints it out

Sergio
  • 6,900
  • 5
  • 31
  • 55
0

Your problem is just timing: JavaScript is executed at its position inside the document. In consequence the DOM, which you access, is probably not completely built.

So in your first example, when the line text = ... is executed, the parser does not know of your form element. Furthermore, your command does not create a reference to the value, but would just copy it.

In the second case, however, just the function is defined (which is fine) and at the time it is called (and your variable text is evaluated) the form element exists and everything works out just fine.

Sirko
  • 72,589
  • 19
  • 149
  • 183
0

You are assigning the value of form on window load and that time the form is not initialize that's why it gives the undefined the value.

If you want to make the var text global then do it:

var text = "";
function printText(){   
    text = document.form1.name.value
    document.write(text);
}

If you will put your script in the end then it initialize the value null as in the starting the value will be the null of input type.

So you need to initialize the variable at the starting and then you can put the value in that.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75