我有一个带有一个表单和许多按钮的网页。 当用户在搜索文本框中按下ENTER时,我想为搜索按钮提交一个POST,其中POST包含搜索按钮的名称。
我见过许多提交表单POST的解决方案,但没有人告诉我如何在POST表单中包含搜索按钮。
这是代码的简化版本:
模板:
<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>
我的观点:
if request.method == POST:
if 'btn_search' in request.POST:
# Do my search
我试过这种方式:
<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>
但是如何在POST数据中包含按钮? 默认情况下,当我按ENTER键时,提交打印按钮 非常感谢你。
答案 0 :(得分:0)
我自己尝试过,并设法使其按以下方式工作。
<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>
脚本发布了&btn-hello&#39;如预期的那样到后端。我还将#importButton更改为#importButton2并发布了&#39; btn-byebye&#39;。
$(document).ready(function () {
$('body').keypress(function (e) {
if (e.keyCode == 13) {
e.preventDefault();
$("#importButton").click();
}
});
});
您的代码中的错误可能在于document.getElementById(&#39; btn_search&#39;)。click();.尝试使用$(&#34;#btn_search&#34;)。click();