function with getElementById not working

    function signup() {
    var username = document.getElementById("user").value
    var password = document.getElementById("pass").value
    if (username != false && password != false) {
        alert("Whats up " + username);
    }
   }

I made a button with an onclick that sets up to signup() and I made 2 text boxes with the ids "username" and "password". For some reason this code doesn't work. Any help? Also I tried to make it just alert username but it still doesn't work.

Edit: Here are the inputs

<form>
<input type="text" class="cool" id="user" placeholder="Username"><br />
<input type="password" class="cool" id="pass" placeholder="Password"><br />
<input type="button" class ="button" value="Sign up" name="signup" onclick="signup()">
</form>

You only need to change the name attribute value of the button to avoid the same as the function name.

Code html will look like this:

<form>
   <input type="text" class="cool" id="user" placeholder="Username"><br />
   <input type="password" class="cool" id="pass" placeholder="Password"><br />
   <input type="button" class ="button" value="Sign up" name="signup-changed" onclick="signup()">
</form>

你提到输入的ID是usernamepassword那么它应该是document.getElementById("username")document.getElementById("password")

  function signup() {
    var username = document.getElementById("username").value
    var password = document.getElementById("password").value
    if (username != false && password != false) {
        alert("Whats up " + username);
    }
   }

Why are you equating to false?

The values of your elements are integers, not Boolean. Writing a compareter of == or !=, you have to use type string.

username == 'string'

Try

    if(username.length > 0 && password.length > 0 )
    {
        alert('hi ' + username);
    }
链接地址: http://www.djcxy.com/p/87676.html

上一篇: 如何将UIViewController的视图添加为子视图

下一篇: 函数getElementById不起作用