0

For my current assignment I am suppose to build a website where people can log in, and post comment. I've never done web programming before so I've been struggling through it. right now I am confused as to how I can use the values from text fields on the html web page in the java script I'm using with the page.

this is the code from my Javascript, (it really doesn't do much of anything I'm just trying to figure out what I'm doing wrong)

   <script type = "text/javascript">
   function inform(name)
   {
  alert(name);
   }
   </script>

and this is what the html looks like where I call the function

<P ALIGN="right">  
        Email: <br><input type="text" name="fname"><br>
        Pass Word: <br><input type="password" name="pass"><br>
        <input type="button" value="Log In" onclick ="inform(document.getElementById('fname').value)"/>
    </P>

When I run this and hit the button it says that the value of name in the inform function is always Null regaurdless of what I put in the name text field. What am I doing wrong?

mlieven
  • 15
  • 1
  • 2
  • 8

2 Answers2

2

You've assigned a name instead of an id.

<!-----------------------------v------------v--->
Email: <br><input type="text" name="fname" id="fname"><br>

As an alternative, you could do this:

<input type="button" value="Log In" onclick ="inform(this.form.fname.value)"/>

And in fact, the this is even optional:

<input type="button" value="Log In" onclick ="inform(form.fname.value)"/>

DEMO: http://jsfiddle.net/kPcmq/

  • Thank you. This is why I love this site, quick and helpful answers – mlieven Apr 06 '13 at 23:03
  • I can't +1 this because it suggests using [obtrusive JavaScript](http://stackoverflow.com/q/5871640/1615483). Not to mention a space before the `=` which makes the HTML invalid anyway. – Paul S. Apr 06 '13 at 23:09
  • 1
    you're just being nit-picky – mlieven Apr 06 '13 at 23:13
  • @PaulS.: I'm using the code from the question. In any case, this isn't the place to have an off-topic discussion about philosophies of "obtrusive JavaScript". –  Apr 06 '13 at 23:17
  • 1
    @PaulS.: And it's not invalid HTML. –  Apr 06 '13 at 23:26
2

You have to change this

Email: <br><input type="text" name="fname"><br>

to Email: <br><input type="text" name="fname" id ="fname" ><br>

Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39