如何用jQuery提交表单中的Enter按钮

如何用jQuery提交表单中的Enter按钮

给出一个HTML表单,任务是使用jQuery在点击’Enter’按钮后提交该表单。为了使用’Enter’按钮提交表单,我们将使用jQuery keypress()方法,为了检查’Enter’按钮是否被按下,我们将使用’Enter’按钮的关键代码值。

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
        crossorigin="anonymous">
    </script>
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h3 style="color: green;font-size: 28px;">
        GeeksforGeeks
    </h3>
  
    <form class="info">
        <input name="fname" /><br>
        <input name="lname" /><br>
        <button type="submit">Submit</button>
    </form>
</body>
  
</html>

JavaScript 代码:

<script>
  
    // Wait for document to load
    (document).ready(() => {
        ('.info').on('submit', () => {
  
            // prevents default behaviour
            // Prevents event propagation
            return false;
        });
    });
    ('.info').keypress((e) => {
  
        // Enter key corresponds to number 13
        if (e.which === 13) {
            ('.info').submit();
            console.log('form submitted');
        }
    })
</script>

Explanation:
我们使用jQuery的event.which来检查按键的键码。回车键的键码是13,所以如果键码符合13,那么我们就使用表单元素上的.submit()方法来提交表单。

Complete 代码:

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
        integrity=
        "sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
        crossorigin="anonymous">
    </script>
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
</head>
  
<body>
    <h3 style="color: green;font-size: 28px;">
        GeeksforGeeks
    </h3>
    <form class="info">
        <input name="fname" /><br><br>
        <input name="lname" /><br><br>
        <button type="submit">Submit</button>
    </form>
  
    <script>
        (document).ready(() => {
            ('.info').on('submit', () => {
                return false;
            });
        });
        ('.info').keypress((e) => {
            if (e.which === 13) {
                ('.info').submit();
                alert('Form submitted successfully.')
            }
        })
    </script>
</body>
  
</html>

输出:
如何用jQuery提交表单中的Enter按钮?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程