Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting input values from text box

I'm trying to get the text from a text box.

I have 2 input text boxes that are not in a form, and I'm trying to retrieve the value and store it in a variable.

This code returns undefined in the alert box that pops up.

<script>
    var userPass = document.getElementById('pass');
    var userName = document.getElementById('fName');
    function submit(){
        alert(userPass.value);
    }
</script>

When I run it with userName.value as a parameter in the alert function, it will work and display what ever you type in the box.

Here is the html:

 <table id="login">
        <tr>
            <td><label>User Name</label></td>
        </tr>
        <tr>
            <td colspan="2"><input class="textBox" id="fName" type="text" maxlength="30"    required/></td>
        </tr>
        <tr>
            <td id="pass"><label>Password</label></td>
        <tr>
            <td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
        </tr>
        <tr>
            <td><input type="button" class="loginButtons" value="Login" onclick="submit();"/>&nbsp&nbsp&nbsp
            <input type="button" class="loginButtons" value="Cancel"/></td>
    </table>
like image 494
Beanno1116 Avatar asked Jan 16 '12 01:01

Beanno1116


2 Answers

You will notice you have no value attr in the input tags.
Also, although not shown, make sure the Javascript is run after the html is in place.

like image 134
Itay Moav -Malimovka Avatar answered Oct 19 '22 11:10

Itay Moav -Malimovka


<script>
  function submit(){
      var userPass = document.getElementById('pass');
      var userName = document.getElementById('user');
      alert(user.value);
      alert(pass.value);
  }
</script>

<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>

like image 27
Emil Carr Avatar answered Oct 19 '22 12:10

Emil Carr