admin管理员组

文章数量:1201371

I have a very simple AJAX form that asks for an email address and sends it to me after submitting.

How can I can I get the form to submit when hitting the enter key?

This runs when user clicks submit button:

<script type="text/javascript">
    $(document).ready(function () {
        $("#submit_btn").click(function () {
            // Get input field values:
            var user_email = $('input[name=email]').val();

            // Simple validation at client's end
            // We simply change border color to red if empty field using .css()
            var proceed = true;
            if (user_email === "") {
                $('input[name=email]').css('border-color', 'red');
                proceed = false;
            }

            // Everything looks good! Proceed...
            if (proceed) {
                /* Submit form via AJAX using jQuery. */
            }
        });

        // Reset previously set border colors and hide all message on .keyup()
        $("#contact_form input, #contact_form textarea").keyup(function () {
            $("#contact_form input, #contact_form textarea").css('border-color', '');
            $("#result").slideUp();
        });
    });
</script>

I know this question has been asked before -- I'm having trouble getting the keypress function to work.

I tried this to no avail:

$("#contact_form").keypress(function (e) {
    if ((e.keyCode == 13) && (e.target.type != "textarea")) {
        e.preventDefault();
        // Get input field values
        var user_email = $('input[name=email]').val();

        // Simple validation at client's end
        // We simply change border color to red if empty field using .css()
        var proceed = true;

        if (user_email === "") {
            $('input[name=email]').css('border-color', 'red');
            proceed = false;
        }

        // Everything looks good! Proceed...
        if (proceed) {
            /* Submit form via AJAX using jQuery. */
        }
    }
});

The form is #contact_form.

Any help would be would appreciated…

I have a very simple AJAX form that asks for an email address and sends it to me after submitting.

How can I can I get the form to submit when hitting the enter key?

This runs when user clicks submit button:

<script type="text/javascript">
    $(document).ready(function () {
        $("#submit_btn").click(function () {
            // Get input field values:
            var user_email = $('input[name=email]').val();

            // Simple validation at client's end
            // We simply change border color to red if empty field using .css()
            var proceed = true;
            if (user_email === "") {
                $('input[name=email]').css('border-color', 'red');
                proceed = false;
            }

            // Everything looks good! Proceed...
            if (proceed) {
                /* Submit form via AJAX using jQuery. */
            }
        });

        // Reset previously set border colors and hide all message on .keyup()
        $("#contact_form input, #contact_form textarea").keyup(function () {
            $("#contact_form input, #contact_form textarea").css('border-color', '');
            $("#result").slideUp();
        });
    });
</script>

I know this question has been asked before -- I'm having trouble getting the keypress function to work.

I tried this to no avail:

$("#contact_form").keypress(function (e) {
    if ((e.keyCode == 13) && (e.target.type != "textarea")) {
        e.preventDefault();
        // Get input field values
        var user_email = $('input[name=email]').val();

        // Simple validation at client's end
        // We simply change border color to red if empty field using .css()
        var proceed = true;

        if (user_email === "") {
            $('input[name=email]').css('border-color', 'red');
            proceed = false;
        }

        // Everything looks good! Proceed...
        if (proceed) {
            /* Submit form via AJAX using jQuery. */
        }
    }
});

The form is #contact_form.

Any help would be would appreciated…

Share Improve this question edited Jun 21, 2015 at 18:21 dragonfire 70211 silver badges18 bronze badges asked Feb 13, 2014 at 2:10 univers_univers_ 4631 gold badge4 silver badges14 bronze badges
Add a comment  | 

8 Answers 8

Reset to default 12

Just bind the submit event to your form, and then the enter key will also work:

$("#contact_form").submit(function (e) {
    e.preventDefault();
    // Get input field values
    var user_email = $('input[name=email]').val();

    // Simple validation at client's end
    // We simply change border color to red if empty field using .css()
    var proceed = true;

    if (user_email === "") {
        $('input[name=email]').css('border-color', 'red');
        proceed = false;
    }

    if (proceed) {
        // Insert the AJAX here.
    }
});

And the code is here: http://jsfiddle.net/6TSWk/6/

add new class in every fieldbox or checkbox => class keypressbutton then replace your code on keypress with this, below :

$(document).on("keypress",".keypressbutton",function(event) {
    var keyCode = event.which || event.keyCode;
    if (keyCode == 13) {
        $("#submit_btn").click();
        return false;
    }
});
$("#myform").keypress(function(event){
    if(event.keycode===13){ // enter key has code 13 
       //some ajax code code here 
       //alert("Enter key pressed");
    }
});

You have two opening brackets in your if statement and miss a closing bracket. Also, I would change e.target.type. Try this:

$("#contact_form").keypress(function (e) {
    if ((e.keyCode == 13) && ($('input[name="email"]').is(':focus'))) {

        e.preventDefault();
        //get input field values
        var user_email = $('input[name=email]').val();

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;

        if (user_email === "") {
            $('input[name=email]').css('border-color', 'red');
            proceed = false;
        }
    }
});

Instead of using button on click function you can use submit button. Load the validate.js file

function validateEmail(email)
{
 var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
 if (reg.test(email))
 {
 return true; }
 else{
 return false;
 }
} 

        $("#test-form").validate({



        submitHandler: function(form) {
            //form.submit();
                var email=$("#email").val();

            if(email=='' )
            {
                // Here you can type your own error message
                $('#valid').css("display","none");
                $('#empty').css("display","block");
                return false;
            }
             if (!(validateEmail(email))) {
                $('#empty').css("display","none");
                $('#valid').css("display","block");
 return false;
 }
            else {
            $.ajax({
            url: "signup.php",
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {


            }            
        });
}
        }
    });

  });

Simple way is this:

In HTML codes:

<form action="POST" onsubmit="ajax_submit();return false;">
    <b>First Name:</b> <input type="text" name="firstname" id="firstname">
    <br>
    <b>Last Name:</b> <input type="text" name="lastname" id="lastname">
    <br>
    <input type="submit" name="send" onclick="ajax_submit();">
</form>

In Js codes:

function ajax_submit()
{
    $.ajax({
        url: "submit.php",
        type: "POST",
        data: {
            firstname: $("#firstname").val(),
            lastname: $("#lastname").val()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            // another codes when result is success
        }
    });
}
<?php
  require_once 'db.php'; 
  if (!empty($_POST['id'])) { 
    $id = $_POST['id'];    
    $sql = "SELECT * FROM district WHERE id = $id"; 
    $query = pg_query($sql);
    echo'<option value=""> select your option </option>';

    if (pg_num_rows($query) > 0) {
      while ($row = pg_fetch_assoc($query)) {
        echo '<option value="' . $row['did'] . '">' . $row['dt'] . 
        '</option>';
      }
    } else {
      echo "<option value=''>No districts found</option>";
    }
  }
?>

Hide preview:

<?php
  require_once 'db.php'; 
  if (!empty($_POST['id'])) { 
    $id = $_POST['id'];    
    $sql = "SELECT * FROM district WHERE id = $id"; 
    $query = pg_query($sql);
    echo'<option value=""> select your option </option>';

    if (pg_num_rows($query) > 0) {
      while ($row = pg_fetch_assoc($query)) {
        echo '<option value="' . $row['did'] . '">' . $row['dt'] . 
        '</option>';
      }
    } else {
      echo "<option value=''>No districts found</option>";
    }
  }
?>

For AJAX requests

After a lot of iterating and experimenting I stumbled on the most concise way I could find to get my AJAX requests working: using a type="submit" button, but hooking into the click event instead of submit:

<button class="submitForm" type="submit"></button>
document.querySelector(".submitForm").addEventListener("click", submitForm() {
   // Function code here
});

This allows you to take advantage of the browser's native support for using Enter to submit the AJAX request, while preventing any double submissions. It also doesn't need any return false or preventDefault() calls. Like I said, concise.

I've confirmed this works in the latest versions of both Firefox and Chrome.

本文标签: javascriptEnter key to submit Ajax formStack Overflow