使用 JavaScript 在文本框中按 Enter 键触发按钮单击

发布于 2024-07-06 15:00:45 字数 366 浏览 11 评论 0原文

我有一个文本输入和一个按钮(见下文)。 当在文本框中按下 Enter 键时,如何使用 JavaScript 触发按钮的单击事件

我的当前页面上已经有一个不同的提交按钮,因此我不能简单地将该按钮设为提交按钮。 而且,我希望 Enter 键在从该文本框内按下时单击此特定按钮,仅此而已。

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

只是在用心讲痛 2024-07-13 15:00:45

在 jQuery 中,以下代码可以工作:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});

$("#pw").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#myButton").click();
    }
});

$("#myButton").click(function() {
  alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>

或者在纯 JavaScript 中,以下代码可以工作:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});

document.getElementById("pw")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myButton").click();
    }
});

function buttonCode()
{
  alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>

In jQuery, the following would work:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});

$("#pw").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#myButton").click();
    }
});

$("#myButton").click(function() {
  alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton">Submit</button>

Or in plain JavaScript, the following would work:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});

document.getElementById("pw")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myButton").click();
    }
});

function buttonCode()
{
  alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password: <input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>

温柔少女心 2024-07-13 15:00:45

然后只需将其编码即可!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>

Then just code it in!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>
天涯沦落人 2024-07-13 15:00:45

弄清楚了这一点:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>
红墙和绿瓦 2024-07-13 15:00:45

让按钮成为提交元素,这样它就会自动进行。

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>

请注意,您需要一个包含输入字段的

元素才能完成此操作(感谢 Sergey Ilinsky)。

重新定义标准行为不是一个好习惯,Enter 键应始终调用表单上的提交按钮。

Make the button a submit element, so it'll be automatic.

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>

Note that you'll need a <form> element containing the input fields to make this work (thanks Sergey Ilinsky).

It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.

迟到的我 2024-07-13 15:00:45

由于还没有人使用过 addEventListener,这里是我的版本。 给定元素:

<input type = "text" id = "txt" />
<input type = "button" id = "go" />

我将使用以下内容:

var go = document.getElementById("go");
var txt = document.getElementById("txt");

txt.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.keyCode == 13)
        go.click();
});

这允许您单独更改事件类型和操作,同时保持 HTML 干净。

注意,确保这在

之外可能是值得的,因为当我将这些元素包含在其中时,按 Enter 键提交了表单并重新加载了页。 我眨了几眼才发现。

<块引用>

附录:感谢 @ruffin 的评论,我添加了缺少的事件处理程序和 preventDefault 以允许此代码(大概)在表单内工作以及。 (我将抽出时间来测试这一点,届时我将删除括号内的内容。)


Since no one has used addEventListener yet, here is my version. Given the elements:

<input type = "text" id = "txt" />
<input type = "button" id = "go" />

I would use the following:

var go = document.getElementById("go");
var txt = document.getElementById("txt");

txt.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.keyCode == 13)
        go.click();
});

This allows you to change the event type and action separately while keeping the HTML clean.

Note that it's probably worthwhile to make sure this is outside of a <form> because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.

Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a preventDefault to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)

捂风挽笑 2024-07-13 15:00:45

在纯 JavaScript 中,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

我注意到回复仅在 jQuery 中给出,因此我考虑也用纯 JavaScript 给出一些内容。

In plain JavaScript,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

情愿 2024-07-13 15:00:45

在现代 JS 中使用 keypressevent.key === "Enter"

const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        document.getElementById("btnSearch").click();
    }
});

Mozilla 文档

支持的浏览器

Use keypress and event.key === "Enter" with modern JS!

const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        document.getElementById("btnSearch").click();
    }
});

Mozilla Docs

Supported Browsers

变身佩奇 2024-07-13 15:00:45

您可以使用一个基本技巧来实现这一点,但我还没有看到完全提及。 如果您想在 Enter 上执行 ajax 操作或其他一些工作,但不想实际提交表单,您可以执行以下操作:

<form onsubmit="Search();" action="javascript:void(0);">
    <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
    <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>

设置 action="javascript:void(0);" 这是从本质上防止默认行为的捷径。 在这种情况下,无论您按下 Enter 键还是单击按钮,都会调用一个方法,并且会调用 ajax 来加载一些数据。

One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

<form onsubmit="Search();" action="javascript:void(0);">
    <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
    <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>

Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

旧夏天 2024-07-13 15:00:45

要在每次按下 Enter 键时触发搜索,请使用以下命令:

$(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        $('#btnSearch').click();
    }
}

To trigger a search every time the enter key is pressed, use this:

$(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        $('#btnSearch').click();
    }
}
铜锣湾横着走 2024-07-13 15:00:45

尝试一下:

<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>

<script>             
   window.onload = function() {
     document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
        if (event.keyCode == 13) {
            document.getElementById('btnSearch').click();
        }
    };

    document.getElementById('btnSearch').onclick =doSomething;
}
</script>

Try it:

<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>

<script>             
   window.onload = function() {
     document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
        if (event.keyCode == 13) {
            document.getElementById('btnSearch').click();
        }
    };

    document.getElementById('btnSearch').onclick =doSomething;
}
</script>
同尘 2024-07-13 15:00:45

纯 JS 工作时间短

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

function doSomething() {
console.log('

Short working pure JS

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

function doSomething() {
  console.log('????');
}
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

情栀口红 2024-07-13 15:00:45
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"

这只是我从最近的一个项目中得到的东西......我在网上找到了它,我不知道在普通的旧 JavaScript 中是否有更好的方法。

onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"

This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.

寒冷纷飞旳雪 2024-07-13 15:00:45

在现代的、未弃用的(没有 keyCodeonkeydown)Javascript 中:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">

In modern, undeprecated (without keyCode or onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">
沩ん囻菔务 2024-07-13 15:00:45

尽管如此,我很确定只要表单中只有一个字段和一个提交按钮,按 Enter 键就应该提交表单,即使页面上还有另一个表单。

然后,您可以使用 js 捕获表单 onsubmit 并执行您想要的任何验证或回调。

Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.

You can then capture the form onsubmit with js and do whatever validation or callbacks you want.

尬尬 2024-07-13 15:00:45

这是适合所有 YUI 爱好者的解决方案:

Y.on('keydown', function() {
  if(event.keyCode == 13){
    Y.one("#id_of_button").simulate("click");
  }
}, '#id_of_textbox');

在这种特殊情况下,我确实使用 YUI 获得了更好的结果触发已注入按钮功能的 DOM 对象 - 但这是另一个故事了......

This is a solution for all the YUI lovers out there:

Y.on('keydown', function() {
  if(event.keyCode == 13){
    Y.one("#id_of_button").simulate("click");
  }
}, '#id_of_textbox');

In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...

东京女 2024-07-13 15:00:45

Angular2 中:

(keyup.enter)="doSomething()"

如果您不希望在按钮中出现一些视觉反馈,那么不引用按钮而是直接调用控制器是一个很好的设计。

另外,不需要 id——这是另一种分离视图和模型的 NG2 方式。

In Angular2:

(keyup.enter)="doSomething()"

If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.

Also, the id isn't needed - another NG2 way of separating between the view and the model.

万人眼中万个我 2024-07-13 15:00:45

如果您还想禁用“发布到服务器”的输入按钮并执行 Js 脚本。

<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
 {document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

This in-case you want also diable the enter button from Posting to server and execute the Js script.

<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
 {document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
墨小沫ゞ 2024-07-13 15:00:45

这个 onchange 尝试很接近,但行为不当浏览器后退然后前进(在 Safari 4.0.5 和 Firefox 3.6.3 上),所以最终我不会推荐它。

<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />

This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.

<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
格子衫的從容 2024-07-13 15:00:45

没有人注意到 html 属性“accesskey”已经可用一段时间了。

这是一种无需 JavaScript 的键盘快捷键方式。

accesskey_browsers

MDN 上的 accesskey 属性快捷方式

打算这样使用。 html 属性本身就足够了,但是我们可以根据浏览器和操作系统更改占位符或其他指示符。 该脚本是一种未经测试的草稿方法来提供想法。 您可能想使用浏览器库检测器,例如小型 bowser

let client = navigator.userAgent.toLowerCase(),
    isLinux = client.indexOf("linux") > -1,
    isWin = client.indexOf("windows") > -1,
    isMac = client.indexOf("apple") > -1,
    isFirefox = client.indexOf("firefox") > -1,
    isWebkit = client.indexOf("webkit") > -1,
    isOpera = client.indexOf("opera") > -1,
    input = document.getElementById('guestInput');

if(isFirefox) {
   input.setAttribute("placeholder", "ALT+SHIFT+Z");
} else if (isWin) {
   input.setAttribute("placeholder", "ALT+Z");
} else if (isMac) {
  input.setAttribute("placeholder", "CTRL+ALT+Z");
} else if (isOpera) {
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>

Nobody noticed the html attibute "accesskey" which is available since a while.

This is a no javascript way to keyboard shortcuts stuffs.

accesskey_browsers

The accesskey attributes shortcuts on MDN

Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

let client = navigator.userAgent.toLowerCase(),
    isLinux = client.indexOf("linux") > -1,
    isWin = client.indexOf("windows") > -1,
    isMac = client.indexOf("apple") > -1,
    isFirefox = client.indexOf("firefox") > -1,
    isWebkit = client.indexOf("webkit") > -1,
    isOpera = client.indexOf("opera") > -1,
    input = document.getElementById('guestInput');

if(isFirefox) {
   input.setAttribute("placeholder", "ALT+SHIFT+Z");
} else if (isWin) {
   input.setAttribute("placeholder", "ALT+Z");
} else if (isMac) {
  input.setAttribute("placeholder", "CTRL+ALT+Z");
} else if (isOpera) {
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>

空心↖ 2024-07-13 15:00:45

对于 jQuery mobile,我必须这样做:

$('#id_of_textbox').live("keyup", function(event) {
    if(event.keyCode == '13'){
    $('#id_of_button').click();
    }
});

For jQuery mobile, I had to do:

$('#id_of_textbox').live("keyup", function(event) {
    if(event.keyCode == '13'){
    $('#id_of_button').click();
    }
});
傾城如夢未必闌珊 2024-07-13 15:00:45
event.returnValue = false

在处理事件时或在事件处理程序调用的函数中使用它。

它至少可以在 Internet Explorer 和 Opera 中运行。

event.returnValue = false

Use it when handling the event or in the function your event handler calls.

It works in Internet Explorer and Opera at least.

一张白纸 2024-07-13 15:00:45

要添加一个完全简单的 JavaScript 解决方案来解决@icedwater 的表单提交问题,这里有一个完整的解决方案,其中 表单

注意:这适用于“现代浏览器”,包括 IE9+。 IE8版本并不复杂,可以在这里学习


小提琴: https://jsfiddle.net/rufwork/gm6h25th/1/

HTML

<body>
    <form>
        <input type="text" id="txt" />
        <input type="button" id="go" value="Click Me!" />
        <div id="outige"></div>
    </form>
</body>

JavaScript

// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
    var go = document.getElementById("go"),
        txt = document.getElementById("txt"),
        outige = document.getElementById("outige");

    // Note that jQuery handles "empty" selections "for free".
    // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
    if (txt && go)    {
        txt.addEventListener("keypress", function (e) {
            if (event.keyCode === 13)   {
                go.click();
                e.preventDefault(); // <<< Most important missing piece from icedwater
            }
        });

        go.addEventListener("click", function () {
            if (outige) {
                outige.innerHTML += "Clicked!<br />";
            }
        });
    }
});

To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form.

NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.


Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/

HTML

<body>
    <form>
        <input type="text" id="txt" />
        <input type="button" id="go" value="Click Me!" />
        <div id="outige"></div>
    </form>
</body>

JavaScript

// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://stackoverflow.com/a/21814964/1028230
document.addEventListener("DOMContentLoaded", function() {
    var go = document.getElementById("go"),
        txt = document.getElementById("txt"),
        outige = document.getElementById("outige");

    // Note that jQuery handles "empty" selections "for free".
    // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
    if (txt && go)    {
        txt.addEventListener("keypress", function (e) {
            if (event.keyCode === 13)   {
                go.click();
                e.preventDefault(); // <<< Most important missing piece from icedwater
            }
        });

        go.addEventListener("click", function () {
            if (outige) {
                outige.innerHTML += "Clicked!<br />";
            }
        });
    }
});
熟人话多 2024-07-13 15:00:45

对于那些可能喜欢简洁和现代 js 方法的人。

input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});

其中 input 是包含输入元素的变量。

For those who may like brevity and modern js approach.

input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});

where input is a variable containing your input element.

芸娘子的小脾气 2024-07-13 15:00:45
document.onkeypress = function (e) {
 e = e || window.event;
 var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
 if (charCode == 13) {

        // Do something here
        printResult();
    }
};

这是我的两分钱。 我正在开发一个适用于 Windows 8 的应用程序,并希望按钮在按下 Enter 按钮时注册单击事件。 我在 JS 中做这个。 我尝试了一些建议,但遇到了问题。 这很好用。

document.onkeypress = function (e) {
 e = e || window.event;
 var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
 if (charCode == 13) {

        // Do something here
        printResult();
    }
};

Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.

獨角戲 2024-07-13 15:00:45

使用 jQuery 执行此操作:

$("#txtSearch").on("keyup", function (event) {
    if (event.keyCode==13) {
        $("#btnSearch").get(0).click();
    }
});

使用普通 JavaScript 执行此操作:

document.getElementById("txtSearch").addEventListener("keyup", function (event) {
    if (event.keyCode==13) { 
        document.getElementById("#btnSearch").click();
    }
});

To do it with jQuery:

$("#txtSearch").on("keyup", function (event) {
    if (event.keyCode==13) {
        $("#btnSearch").get(0).click();
    }
});

To do it with normal JavaScript:

document.getElementById("txtSearch").addEventListener("keyup", function (event) {
    if (event.keyCode==13) { 
        document.getElementById("#btnSearch").click();
    }
});
傾旎 2024-07-13 15:00:45

在 jQuery 中,您可以使用 event.which==13。 如果您有表单,则可以使用$('#formid').submit()(将正确的事件侦听器添加到所述表单的提交中)。

$('#textfield').keyup(function(event){
   if(event.which==13){
       $('#submit').click();
   }
});
$('#submit').click(function(e){
   if($('#textfield').val().trim().length){
      alert("Submitted!");
   } else {
    alert("Field can not be empty!");
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="textfield">
Enter Text:</label>
<input id="textfield" type="text">
<button id="submit">
Submit
</button>

In jQuery, you can use event.which==13. If you have a form, you could use $('#formid').submit() (with the correct event listeners added to the submission of said form).

$('#textfield').keyup(function(event){
   if(event.which==13){
       $('#submit').click();
   }
});
$('#submit').click(function(e){
   if($('#textfield').val().trim().length){
      alert("Submitted!");
   } else {
    alert("Field can not be empty!");
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="textfield">
Enter Text:</label>
<input id="textfield" type="text">
<button id="submit">
Submit
</button>

仅此而已 2024-07-13 15:00:45

如今,change 事件就是这样!

document.getElementById("txtSearch").addEventListener('change',
    () => document.getElementById("btnSearch").click()
);

These day the change event is the way!

document.getElementById("txtSearch").addEventListener('change',
    () => document.getElementById("btnSearch").click()
);
给我一枪 2024-07-13 15:00:45

我的可重用 Vanilla JS 解决方案。 因此您可以根据哪个元素/文本框处于活动状态来更改点击哪个按钮。

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}

My reusable Vanilla JS solution. so you can change which button gets hit depending on what element/textbox is active.

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}
書生途 2024-07-13 15:00:45

您可以在 jQuery 中尝试以下代码。

$("#txtSearch").keyup(function(e) {
    e.preventDefault();
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode === 13 || e.key === 'Enter') 
    {
        $("#btnSearch").click();
    }
});

You can try below code in jQuery.

$("#txtSearch").keyup(function(e) {
    e.preventDefault();
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode === 13 || e.key === 'Enter') 
    {
        $("#btnSearch").click();
    }
});
滥情哥ㄟ 2024-07-13 15:00:45

我开发了自定义 javascript,只需添加类即可实现此功能

示例:

在这里查看 < a href="https://jsfiddle.net/RaviMakwana/k6zL1q9t/" rel="nofollow noreferrer">小提琴

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
    if(banner.hasClass("alt"))
    banner.removeClass("alt")
  else
    banner.addClass("alt")
})

$(document).ready(function(){
    $(document).on('keydown', function (e) {
        
         if (e.ctrlKey) {
            $('[class*="ctrl-"]:not([data-ctrl])').each(function (idx, item) {
                var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();
                $(item).attr("data-ctrl", Key);
                $(item).append('<div class="tooltip fade top in tooltip-ctrl alter-info" role="tooltip" style="margin-top: -61px; display: block; visibility: visible;"><div class="tooltip-arrow" style="left: 49.5935%;"></div><div class="tooltip-inner"> CTRL + ' + Key + '</div></div>')
            });
        }
         
        if (e.ctrlKey && e.which != 17) {
            var Key = String.fromCharCode(e.which).toLowerCase();
            if( $('.ctrl-'+Key).length == 1) {
                e.preventDefault();
                if (!$('#divLoader').is(":visible"))
                    $('.ctrl-'+Key).click();
                console.log("You pressed ctrl + "+Key );
            }
        }
    });
    $(document).on('keyup', function (e) {
        if(!e.ctrlKey ){
          $('[class*="ctrl-"]').removeAttr("data-ctrl");
            $(".tooltip-ctrl").remove();
        }
    })
});
#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button class="ctrl-s" title="s">Change color</button><br/><br/>
  <span>Press CTRL+S to trigger click event of button</span>
</div>

-- 或 --
查看运行示例
https://stackoverflow.com/a/58010042/6631280

注意:在当前逻辑上,您需要按 Ctrl +
输入

I have developed custom javascript to achieve this feature by just adding class

Example: <button type="button" class="ctrl-p">Custom Print</button>

Here Check it out Fiddle

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
    if(banner.hasClass("alt"))
    banner.removeClass("alt")
  else
    banner.addClass("alt")
})

$(document).ready(function(){
    $(document).on('keydown', function (e) {
        
         if (e.ctrlKey) {
            $('[class*="ctrl-"]:not([data-ctrl])').each(function (idx, item) {
                var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();
                $(item).attr("data-ctrl", Key);
                $(item).append('<div class="tooltip fade top in tooltip-ctrl alter-info" role="tooltip" style="margin-top: -61px; display: block; visibility: visible;"><div class="tooltip-arrow" style="left: 49.5935%;"></div><div class="tooltip-inner"> CTRL + ' + Key + '</div></div>')
            });
        }
         
        if (e.ctrlKey && e.which != 17) {
            var Key = String.fromCharCode(e.which).toLowerCase();
            if( $('.ctrl-'+Key).length == 1) {
                e.preventDefault();
                if (!$('#divLoader').is(":visible"))
                    $('.ctrl-'+Key).click();
                console.log("You pressed ctrl + "+Key );
            }
        }
    });
    $(document).on('keyup', function (e) {
        if(!e.ctrlKey ){
          $('[class*="ctrl-"]').removeAttr("data-ctrl");
            $(".tooltip-ctrl").remove();
        }
    })
});
#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button class="ctrl-s" title="s">Change color</button><br/><br/>
  <span>Press CTRL+S to trigger click event of button</span>
</div>

-- or --
check out running example
https://stackoverflow.com/a/58010042/6631280

Note: on current logic, you need to press Ctrl +
Enter

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文