[英]Submit a certain button when ENTER is pressed
I have a web page with one form and many buttons. 我有一个带有一个表单和许多按钮的网页。 I want to submit a POST for the search button when the user presses ENTER in the search textbox where the POST holds the name of the search button. 当用户在搜索文本框中按下ENTER时,我想为搜索按钮提交POST,其中POST包含搜索按钮的名称。
I have seen many solutions to submit a POST of a form, but none of them told me how to include the search button within the form POST. 我见过许多提交表单POST的解决方案,但没有一个告诉我如何在POST表单中包含搜索按钮。
This is a simplified version of the code: 这是代码的简化版本:
The template: 模板:
<form name="form" id="form" action="" method="POST">
<input type="text" id="txtbx_search" name="txtbox_search">
<button id="btn_print" type="submit" name="btn_print"><b>Print</b> </button>
<button id="btn_delete" type="submit" name="btn_delete"><b> Delete</b> </button>
<button id="btn_search" type="submit" name="btn_search"><b>Search</b> </button>
{% csrf_token %}
</form>
My views: 我的观点:
if request.method == POST:
if 'btn_search' in request.POST:
# Do my search
I have tried this way: 我试过这种方式:
<script>
$(document).ready(function () {
$('#txtbx_search').keypress(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
document.getElementById('btn_search').click();
//OR
document.getElementById('form').submit();
}
});
});
</script>
But how can I include the button within the POST data? 但是如何在POST数据中包含按钮? By default, when I press ENTER, the print button is submitted Thank you very much. 默认情况下,当我按下ENTER时,提交打印按钮非常感谢。
I tried this myself and managed to make it work the following way. 我自己尝试了这个并设法使它按以下方式工作。
<form id="importForm" method="post" enctype="multipart/form-data">
<div class="row" style="text-align:center">
<button id="importButton" type="submit" class="btn btn-primary" name="btn-hello">
<span class="glyphicon glyphicon-upload" aria-hidden="true"></span> Import
</button>
<button id="importButton2" type="submit" class="btn btn-primary" name="btn-byebye">
<span class="glyphicon glyphicon-upload" aria-hidden="true"></span> Import
</button>
</div>
</form>
The script posts 'btn-hello' to the backend as expected. 该脚本按预期将'btn-hello'发布到后端。 I also changed #importButton to #importButton2 and it posted 'btn-byebye'. 我还将#importButton更改为#importButton2并发布了'btn-byebye'。
$(document).ready(function () {
$('body').keypress(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
$("#importButton").click();
}
});
});
Perhaps the fault in your code lies in document.getElementById('btn_search').click();. 您的代码中的错误可能在于document.getElementById('btn_search')。click();. Try to use $("#btn_search").click(); 尝试使用$(“#btn_search”)。click();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.