我有一个数组,其数据显示在表格中。 Live Code
按日期或按名称过滤效果很好。
我写了一些代码来显示"没有找到数据"如果用户输入的名称不在列表中,但某种程度上它不起作用。
如果用户只输入与名单上的姓氏或名字相匹配的姓氏或名字,是否可以编写显示结果的代码?
请伸出援助之手。谢谢!
HTML
<p>From: <input class="datepicker" id="dateFrom" type="text"> To: <input class="datepicker" id="dateTo" type="text"><button class="buttApply">APPLY</button></p>
Search by Name<input type="text" id="searchByName"><button type="button" id="byNamebutton">SEARCH</button><span id="errmsg"></span>
<div class="text"></div>
<table id="myTable" border="1" width="300" cellpadding="5">
</table>
JS
$( ".datepicker" ).datepicker();
var dateList =[
{
name: "Mike Jenson",
email: "mike_j@yesware.com",
phone: "9433550193",
joined: "05/23/2014",
},
{
name: "Jim Stevens",
email: "jim_s@yesware.com",
phone: "1299331944",
joined: "05/22/2014"
},
{
name: "Paul Smith",
email: "paul_s@yesware.com",
phone: "4351289654",
joined: "04/14/2014"
},
{
name: "Sarah Andrews",
email: "sarah_a@yesware.com",
phone: "1299332944",
joined: "03/15/2014"
},
{
name: "Edward O'Brien",
email: "edward_ob@yesware.com",
phone: "4782456897",
joined: "03/27/2014"
},
{
name: "Nicole Plano",
email: "nicole_p@yesware.com",
phone: "6657831564",
joined: "03/30/2013"
},
{
name: "Peter Min",
email: "peter_m@yesware.com",
phone: "8893923938",
joined: "01/07/2013"
},
{
name: "Aaron Jackson",
email: "aaron_j@yesware.com",
phone: "6174896315",
joined: "04/11/2014"
}
];
$('#byNamebutton').click(
function()
{
var Namefilter = dateList.filter(function(NameItem)
{
if(NameItem.name == $('#searchByName').val())
{
return NameItem.name == $('#searchByName').val();
}
else
{
$('#mytable').append('No data found!');
}
});
refreshTable(Namefilter);
}
);
$('.buttApply').click(
function()
{
var filtered = dateList.filter(function(item){
return item.joined >= $('#dateFrom').val() && item.joined <= $('#dateTo').val();
});
refreshTable(filtered);
}
);
function refreshTable(list){
$("#myTable").html("");
for (var i=0; i< list.length; i++)
{
var tr="<tr>";
var td1 = "<td>" + list[i]["name"] + "</td>";
var td2 = "<td>" + list[i]["email"] + "</td>";
var td3 = "<td>" + list[i]["phone"] + "</td>";
var td4 = "<td>" + list[i]["joined"] + "</td></tr>";
$('#myTable').append(tr+td1+td2+td3+td4);
}
}
refreshTable(dateList);
答案 0 :(得分:1)
如果您希望按名称搜索按包含短语的方式工作并忽略区分大小写:
return NameItem.name.toLowerCase().indexOf($('#searchByName').val().toLowerCase()) != -1;
至于找不到数据,您只需要在reFreshTable函数的末尾包含它:
if(list.length==0){
$('#myTable').html("No Data Found");
}
JsFiddle:http://jsfiddle.net/juvian/WWscZ/9/
我还建议如果您的数据不是很大,可以更改$('#byNamebutton').click(
$('#searchByName').keyup(
以使其更具响应性,因为它会在您输入时进行过滤
答案 1 :(得分:0)
对于#1,在第91行添加,
if ($('#myTable').html() == "") {
var tr="<tr>";
var td1 = "<td colspan=4>No Results Found</td></tr>";
$('#myTable').append(tr+td1);
}
这解决了你的#2问题:
indexOf返回另一个字符串中字符串的位置。如果未找到,则返回-1:
在第59行,请改用:
return NameItem.name.indexOf($('#searchByName').val()) > -1;
它将搜索部分匹配而不是整个匹配。所以如果你搜索&#34; Mike&#34;或&#34; Jensen&#34;它将返回&#34; Mike Jensen&#34;。