繁体   English   中英

JS Jquery从搜索/过滤器输入中删除连字符(仅数字)

[英]JS Jquery Removing hyphen from search/filter input (numbers only)

我有一个搜索输入字段,其中包含一些已连接的JavaScript,可用作页面上的过滤器。 它基本上接受输入并在h3标记中搜索名称和描述,然后还搜索一个表(特别是tbody-> tr),如果某行不包含匹配项,则将其隐藏。

我遇到了表主体/行的内容的一个问题。 每行都有一个数字,通常为6位数字,后接连字符4,但并非总是如此(1234-56、9876-54等)。

问题是:如果您用连字符搜索数字,它会正确过滤并仅显示该数字,但如果您键入不带连字符的6位数字,则会隐藏所有内容,因为从技术上讲,由于它搜索精确的字符串而找不到匹配项。

我发现了几种方法,但它们仅适用于filter变量,但是即使这只是一个很小的解决方法,我也需要一些帮助。 基本上,当在tbody / tr中寻找匹配项时,我需要它忽略连字符。 因此,无论我键入123456还是1234-56,它只会显示匹配项为1234-56的行。 我希望这是有道理的。

Javascript:

<script type = "text/javascript">
$(document).ready(function(){
$("#srch-term").keyup(function(){
//For entered search values
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
var search_regex = new RegExp(filter, "i");

// Loop through the main container as well as the table body and row that contains the match
$(".group-container").each(function(){
    //check if filter matches the group name or description
    var group_name = $(this).children('h3').text()
    var group_description = $(this).children('.uk-text-muted').text()

    if(group_name.search(search_regex)>=0 || group_description.search(search_regex)>=0){ // filter matches
        $(this).show() // show group
        $(this).find("tbody tr").show() // and all children
        return // skip tr filtering
    }

    var no_matches = true

    $(this).find("tbody tr").each(function(){

        // If the list item does not contain the text phrase fade it out
        if ($(this).text().replace('Available','').search(search_regex) < 0) {
            $(this).hide();

        // Show the list item if the phrase matches and increase the count by 1
        } else {
            $(this).show();
            count++;
            no_matches = false
        }
    });

    if(no_matches){ // if no tr matched the search either, hide whole group
        $(this).hide();
    }

    });
  });
});
</script>

如果用连字符搜索数字,则它会正确过滤并仅显示该数字,但如果您键入不带连字符的6位数字,则它将隐藏所有内容,因为从技术上讲,由于它搜索精确的字符串而找不到匹配项。

如果您只想进行基于数字的搜索,请在使用比较时从网格文本中删除非数字字符

.replace(/\D/g, "");

并使其

var group_name = $(this).children('h3').text().replace(/\D/g, "");
var group_description = $(this).children('.uk-text-muted').text().replace(/\D/g, "");

然后

if ($(this).text().replace(/\D/g,'').search(search_regex) < 0) {
        $(this).hide();
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM