[英]DataTables search on button click instead of typing in input
I would to know if it is possible to move the search function out of an input
for a table modified by DataTables
. 我想知道是否可以将搜索功能移出DataTables
修改的表的input
。 Currently I have a custom input that executes this function: 目前我有一个执行此功能的自定义输入:
<script>
$(document).ready(function() {
var oTable = $('#staffTable').DataTable();
$('#searchNameField').keyup(function () {
oTable.search($(this).val()).draw();
});
})
</script>
the input looks like so: 输入看起来像这样:
<label for="searchNameField" class="col col-form-label">Name:</label>
<div class="col-sm-11">
<input type="text" class="form-control ml-0 pl-2" id="searchNameField"
placeholder="Name" autofocus/>
</div>
What I would like to do is move this to a button. 我想做的是将其移动到一个按钮。 What I thought might be possible is the following: 我认为可能的是以下内容:
<script>
$(document).ready(function() {
var oTable = $('#staffTable').DataTable();
$('#searchButton').click(function () {
oTable.search($(this).val()).draw();
});
})
</script>
with the button looking like so: 按钮看起来像这样:
<button id="searchButton" type="button" class="btn btn-sm btn-success" style="width: 150px">
<i class="fa fa-search">
Search
</i>
</button>
however when I click on the button this does not work. 但是,当我点击按钮时,这不起作用。 In typing this question I have realised that this is probably because when I click the button, it does not know where to get the filter text from to actually filter the table. 在输入这个问题时,我意识到这可能是因为当我点击按钮时,它不知道从哪里获取过滤器文本来实际过滤表格。
Is there a way I can have a button click that references the input, that then goes and filters the table? 有没有办法我可以点击一个按钮来引用输入,然后去过滤表?
You're right, you need to redefine $(this)
, which now refers to the button, not the search box: 你是对的,你需要重新定义$(this)
,现在指的是按钮,而不是搜索框:
$(document).ready(function() {
var oTable = $('#staffTable').DataTable();
$('#searchButton').click(function () {
oTable.search($("#searchNameField").val()).draw();
});
// EDIT: Capture enter press as well
$("#searchNameField").keypress(function(e) {
// You can use $(this) here, since this once again refers to your text input
if(e.which === 13) {
e.preventDefault(); // Prevent form submit
oTable.search($(this).val()).draw();
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.