【问题标题】:JS Jquery Removing hyphen from search/filter input (numbers only)JS Jquery 从搜索/过滤输入中删除连字符(仅限数字)
【发布时间】:2017-11-22 13:57:13
【问题描述】:

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

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

问题是:如果您搜索带有连字符的数字,它会正确过滤并仅显示该数字,但如果您只键入没有连字符的 6 位数字,它会隐藏所有内容,因为它在技术上没有找到匹配项搜索确切的字符串。

我找到了一些方法来做到这一点,但它们只适用于过滤器变量,但我需要一些帮助,即使它只是一个小的解决方法。基本上,在 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>

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    如果您搜索带有连字符的数字,它会正确过滤并 仅显示该数字,但如果您只输入 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();
     }
    

    【讨论】:

    • 我可能只是感到困惑,但我不确定这是否正是我要去的地方。用户还可以按沙发、双人沙发、椅子等进行搜索。但是如果他们按项目编号搜索,那么他们将搜索 123456 或 1234-56,所以我仍然需要现有的基于文本的搜索,只要他们输入数字然后它会拉出那个连字符
    • 那么,您想根据用户要搜索的内容来准备您的数据以进行不同的搜索吗?在执行我上面给出的特定 replace 之前,您可以检查输入是否全是数字。
    猜你喜欢
    • 2013-04-02
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2012-06-26
    • 2018-11-13
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    相关资源
    最近更新 更多