从输入jquery获取值

时间:2015-03-12 00:30:13

标签: javascript jquery forms

我正在尝试从输入中获取值并将其传递给脚本以注册用户,但没有任何运气存储它。我设置为测试的警报没有显示任何值。以下是我必须获取用户名的值并将其传递给脚本:

                    <form id ="form-signin" class="form-signin" action="" method="">
                      <input type="text" id="username" class="form-control" placeholder="Username" required autofocus>
                      <input type="email" class="form-control" placeholder="Email" required autofocus>
                      <input type="password" class="form-control" placeholder="Password" required>
                      <input type="submit" id="createUser" class="btn btn-lg btn-default btn-block" value="Sign Up" />
                    </form>



<script type="text/javascript">

    Parse.initialize("u3BTp3Efoko8hbNhl5MCeli8Kd2iiEk8mE4vYgn4", "tQEGymAWeB8Tr2LA3YDGoq2Lt2xpGMW9ikeFSTtD");

    //get the input data
    var username = $('#username').val();

    //set the user
    var user = new Parse.User();

    $( "form" ).submit(function( event ) {

      alert( "Error: " + username + " " );

        user.set("username", " " + username + " ");
        user.set("password", "my pass");
        user.set("email", "email@example.com");

        // other fields can be set just like with Parse.Object
        user.set("phone", "415-392-0202");

        user.signUp(null, {
          success: function(user) {
            // Hooray! Let them use the app now.
          },
          error: function(user, error) {
            // Show the error message somewhere and let the user try again.
            alert("Error: " + error.code + " " + error.message);
          }
        });

    });

</script>

1 个答案:

答案 0 :(得分:2)

您需要在提交处理程序中读取用户名的值。

当正在加载页面时,您正在读取字段#username的值,该页面为空白,一旦您读取该值并将其分配给变量,则在更新输入时变量值将不会更新值。

//dom ready handler
jQuery(function ($) {
    Parse.initialize("u3BTp3Efoko8hbNhl5MCeli8Kd2iiEk8mE4vYgn4", "tQEGymAWeB8Tr2LA3YDGoq2Lt2xpGMW9ikeFSTtD");

    //set the user
    var user = new Parse.User();

    $("form").submit(function (event) {
        //get the input data
        var username = $('#username').val();//read the user value in s

        alert("Error: " + username + " ");

        user.set("username", " " + username + " ");
        user.set("password", "my pass");
        user.set("email", "email@example.com");

        // other fields can be set just like with Parse.Object
        user.set("phone", "415-392-0202");

        user.signUp(null, {
            success: function (user) {
                // Hooray! Let them use the app now.
            },
            error: function (user, error) {
                // Show the error message somewhere and let the user try again.
                alert("Error: " + error.code + " " + error.message);
            }
        });

    });
})