jQuery/AJAX login form submit on enter

前端 未结 3 1391
天涯浪人
天涯浪人 2020-12-19 15:52

I have a fairly simple login form that is submitted with a jQuery AJAX request. Currently, the only way to submit it is to press the \"Login\" button, but I would like to be

相关标签:
3条回答
  • 2020-12-19 16:35

    Add an ID to your form and transform your login button into a submit button :

    <form id="myform">
    
    <label for="username">Username</label>
    <input type="text" id="username" placeholder="Username" />
    
    <label for="password">Password</label>
    <input type="text" id="password" placeholder="Password" />
    
    <input type="submit" id="login" value="Login"/>
    
    </form>
    

    Then, instead of using the click event:

    $('#login').click(function() {
    

    use the submit event:

    $('#myform').submit(function() {
    
    0 讨论(0)
  • 2020-12-19 16:47
    ​$('form').on('keyup', function(e){
        if(e.which == 13 || e.keyCode == 13){
            alert('enter pressed');
        }        
    });​​
    
    0 讨论(0)
  • 2020-12-19 16:49

    HTML

    <form id='myfrm'>
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Username" />
    
        <label for="password">Password</label>
        <input type="text" id="password" placeholder="Password" />
    
        <button id="login">Login</button> 
    </form>
    

    JavaScript:

    $(document).ready(function() {
    
        $('#myform').submit(function() {
    
            $.ajax({
                type: "POST",
                url: 'admin/login.php',
                data: {
                    username: $("#username").val(),
                    password: $("#password").val()
                },
                success: function(data)
                {
                    if (data === 'Correct') {
                        window.location.replace('admin/admin.php');
                    }
                    else {
                        alert(data);
                    }
                }
            });
            //this is mandatory other wise your from will be submitted.
            return false; 
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题