1

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>
peakersky
  • 81
  • 5

2 Answers2

3

Try the following:

<!DOCTYPE html>
<html>
  <head> 
    
    <script type='text/javascript'>
    
      function onLoadFunction(){
      
        document.getElementById('text_input').value = '123';
      
      }
      
    </script>
      
  </head>
  <body onload="onLoadFunction()">
    
     <input type='text' id='text_input' value='' />
    
   </body>
</html>
R. Jones
  • 255
  • 2
  • 11
0

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

Vicky Kumar
  • 1,236
  • 11
  • 25