peakersky peakersky - 2 months ago 7
HTML Question

Setting values for a textfield by .value

I know that this should be a really easy question, but I have no idea why a value cannot be assigned to a text field? I've also tried the getElementById by assigning the input an id, but that too doesn't work. I've been struggling with this for the past 3hours. Am I doing something completely wrong?

Javascript is

document.form1.hello.value= "123";


HTML is

<form name="form1" class="" action="index.html" method="post">
<input type="text" name="hello" value="">
</form>


Uncaught TypeError: Cannot read property 'hello' of undefined is the error.

full version is

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
document.form1.hello.value= "123";
</script>
</head>
<body>
<form name="form1" class="" action="index.html" method="post">
<input type="text" name="hello" value="">
</form>
</body>
</html>

Answer

Hi peak your code is working fine

<form name="form1" class="" action="index.html" method="post">
 <input type="text" name="hello" value="">
</form>

document.form1.hello.value= "123"

please check this code pen for me it is working fine verify once http://codepen.io/vkvicky-vasudev/pen/ZpBbkR

the code which you have written in that put script tag inside body

<html>
<head>
<meta charset="utf-8">
<title></title>

</head>
<body>
<form name="form1" class="" action="index.html" method="post">
  <input type="text" name="hello" value="">
</form>
 <script type="text/javascript">
    document.form1.hello.value= "123";
 </script>
 </body>
 </html>

here is code pen http://codepen.io/vkvicky-vasudev/pen/YGpymP