.val()不起作用 - 无法找到解决方案

时间:2013-06-09 16:06:05

标签: javascript jquery

$(document).ready(function() {
 var login = $("#login").val();
 var password = $('#password').val();


 $('.login-button').click(function() {
  alert(login);
 });
});

HTML

<form method="post" class="login">  <p id="login-error"></p>
<p>
  <label for="login">Username:</label>
  <input type="text" name="login" id="login" placeholder="username">
</p>

<p>
  <label for="password">Password:</label>
  <input type="password" name="password" id="password" placeholder="password">
</p>

<p class="login-submit">
  <button class="login-button">Login</button>
</p>

<p class="forgot-password">Fill your username and password.</p>   </form>

它没有显示!怎么了?有解决方案吗id名称是正确的

编辑: 我有另一个问题。不想为此打开另一个问题。我正在尝试从validate.php获取ajax答案(它位于/views/admin/validate.php - 它在打开domain.com/validate时运行)

$(document).ready(function() {  
$('.login-button').click(function() {
var login = $("#login").val();
var password = $('#password').val();
$.ajax({
  type: 'POST',
  url: '/view/admin/validate.php',
  data: {
  login : login,
  password : password
  },
  success: function(data){
    $('#login-error').html(data);
  }
});
});
});

validate.php

<?php
session_start();
$user = mysql_real_escape_string($_POST['login']);
$password = mysql_real_escape_string(sha1($_POST['password']));
$query = mysql_query("SELECT * FROM  `users` WHERE name =  '$user' AND pass =  '$password' AND privileges = 'superuser'");
$num_rows = mysql_num_rows($query);
if($num_rows == '0') {
echo "Username and Password are incorrect! (Maybe you don't have permission!)";
}
elseif($num_rows == '1') {
$expire = time()*60*60*60*60;
setcookie("user","$user",$expire);
$_SESSION['user'] = $user;
include '/views/admin/admin.php';
}
?>

应该返回用户名和密码不正确! (也许你没有许可!) - 但它没有..任何解决方案??

3 个答案:

答案 0 :(得分:5)

var login = $("#login").val();

当此行运行时,输入为空。

您需要在用户输入内容后获取值。

答案 1 :(得分:0)

$('.login-button').click(function() {
  var login = $('#login').val();
  alert(login);
 });

答案 2 :(得分:0)

试一试:

$('.login-button').click(function() {
  alert($("#login").val());
 });

或:

$('.login-button').click(function() {
      var login = $("#login").val();
      alert(login);
     });

或:

var login = "";
$('.login-button').click(function() {
      login = $("#login").val();
      alert(login);
     });