0

So recently, I have been trying to implement the keyup function for search after fetching data from database. I have searched quite a few questions on this and did manage to find a regex expression for matching numbers in order

Regex for numbers only

which gave me this expression "^[0-9]+$". I have also searched another question with a regex expression with regards to jquery code in realtime search

How to perform a real time search and filter on a HTML table

So I tried changing regex expression differently to the one in the first question for numbers in a specific order but then it does not seem to work

http://jsfiddle.net/qw5z5abo/

This is my jsfiddle code which I am trying to make work before implementing in my real code so question is which part am I doing it wrongly and how do I also make regex accept only 10 characters? Thanks in advance.

HTML

<input type="text" id="search" placeholder="Type to search">
<table id="table">
 <tr>
  <td>3123124</td>
  <td>438785345</td>
</tr>
<tr>
  <td>123131234</td>
  <td>31234144</td>
</tr>
<tr>
  <td>8909808</td>
  <td>8709090980</td>
</tr>
</table>

JS

var $rows = $('#table tr');
$('#search').keyup(function() {

 var reg = RegExp("^[0-9]+$"), text;

$rows.show().filter(function() {
    text = $(this).val();
    return !reg.isMatch(text);
}).hide();
});

This is the input and result. Result will be shown in a table.

$(".navbar-search").one('click', function(){
$.ajax({
    url: "http://localhost:3000/api/queryAllRecord", // server url
    type: "POST", //POST or GET
    contentType: "application/json",
     // data to send in ajax format or querystring format
    dataType : "JSON", //dataType is you telling jQuery what kind of 
                       response to expect
    success: function(response) {
        alert('success');
         if(response){
            var len = response.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    if(response[i].samID && response[i].itemDescription){
                        txt += "<tr class='rowdata'>
                                <td>"+response[i].samID+"</td>"
                                +"<td>"+response[i].itemDescription+"</td>"
                                +"<td 
                                class='editNumber'>"+response[i].issuedQTY + 
                                "</td>"+"<td 
                                class='editNumber'>"+response[i].openingQTY 
                                + "</td>" + "<td 
                               class='editNumber'>"+response[i].closingQTY+"
                               </td>" +"<td 
                             class='editNumber'>"+response[i].corruptedQTY+"
                               </td>" +"<td>"+response[i].Remarks+"</td>"+"
                               <td>"+response[i].ntaRequestRef+"</td>"
                               +"<td><input class='input button-edit' 
                               type='submit' id='edit' value='Edit' onclick 
                               = 'edit(this)' /></td>" 
                               +"<td><input class='input button-edit' 
                              type='button' id='delete' value='Delete' 
                              onclick='deleteResult(this)' /></td>"+"</tr>";
                    }
                }

                $("#bResults").empty();
                if(txt != ""){
                    $("#results").removeClass("hidden");
                    $("#bResults").append(txt);
                }
            }
        }
    },
    error: function(response) {
        alert('error');
    }
});
event.preventDefault();
});

This is the search that will be executed which will then fetch data from database and put it in a table then I will input search on keyup for searching. Expected input should be something like this 1607180511 and while typing, it is filtering according to what the user typed like if lets say he typed 1607, all those with 1607... should appear or if it is 1607180511 then it will show results of that as well. This is the fiddle code. Sorry for my format of asking questions.

Ong Kong Tat
  • 1,172
  • 2
  • 9
  • 22
  • Can you include input and expected result at Question? – guest271314 Jul 14 '17 at 03:26
  • @guest271314 oh do you mean the code with my input and result? – Ong Kong Tat Jul 14 '17 at 03:28
  • 1
    you mean the input accept only 10 characters? use `maxlength="10"` – Atmahadli Jul 14 '17 at 03:32
  • What is expected input and what is expected result of `RegExp`? – guest271314 Jul 14 '17 at 03:33
  • @guest271314 Hi, I have updated my question ' – Ong Kong Tat Jul 14 '17 at 03:37
  • @Atmahadli Thanks for the input. I will add that to mine after my regex is working. – Ong Kong Tat Jul 14 '17 at 03:37
  • Where is `RegExp` used at JavaScript at Question? – guest271314 Jul 14 '17 at 03:43
  • @guest271314 Added to my question – Ong Kong Tat Jul 14 '17 at 03:45
  • `` is an `HTML` element – guest271314 Jul 14 '17 at 03:46
  • I've voted to close because questions are supposed to show the relevant code directly in the question body rather than relying on external links, and you've shown irrelevant Ajax code but *not* the actual regex search function you're asking about. Though in any case for what you are trying to achieve you don't need regex at all, you can just use the `:contains()` selector: http://jsfiddle.net/qw5z5abo/3/ (you would need to validate the input, but then you'd need to do that for a regex solution too, so...) – nnnnnn Jul 14 '17 at 03:50
  • If you want to use a regex to filter: http://jsfiddle.net/n1qrt6av/4/ – T4rk1n Jul 14 '17 at 04:01
  • @nnnnnn Not sure about what you mean but I have already added it jsfiddle from the link which shows the regex function unless you are meaning something else and I am saying the numbers need to be in a specific order which means 1608 will search for (1608...) not (...1608...) – Ong Kong Tat Jul 14 '17 at 04:30
  • @guest271314 Do you mean this `RegExp("^[0-9]+$")`? – Ong Kong Tat Jul 14 '17 at 04:31
  • @T4rk1n I mean in a specific order whereby the number has to be in that position for 1 and 2 in the second position like 1608 will search for (1608...) not (...1608...) – Ong Kong Tat Jul 14 '17 at 04:32
  • Yes, you added a fiddle, but as I said, "questions are supposed to show the relevant code **directly in the question body** rather than relying on external links". It's fine to add a fiddle as well, but not on its own. The question wording is unclear, but if the requirement is to do a "starts with" search then ignore my previous `:contains()` suggestion. – nnnnnn Jul 14 '17 at 04:39
  • @nnnnnn Ah I see I get what you mean. I will keep that in mind when asking questions in the future and will change the one here now – Ong Kong Tat Jul 14 '17 at 04:40
  • @OngKongTat then remove the 'g' from match. – T4rk1n Jul 14 '17 at 04:44
  • @T4rk1n Doesn't seem to happen if I get what you mean correctly. Jsfiddle contains yours without 'g' http://jsfiddle.net/c4u3e59c/ – Ong Kong Tat Jul 14 '17 at 04:46

1 Answers1

1

My understanding of your requirement is that you want a "starts with" search. That is, when the user types something in the search field, you want to show only the table rows that have one or more cells starting with the entered value.

In that case you don't want to use a regex like ^[0-9]+$ which tests whether the string is composed of nothing but digits, you need to match on the value entered by the user. You could turn that value into a regex, but it is simpler to just use the string .indexOf() method - if the result of stringToSearch.indexOf(searchString) is 0 that means that searchString was found at the beginning of stringToSearch (whereas a return of -1 means it wasn't found, and greater than 0 means it was found but not at the beginning).

In your function, text = $(this).val(); doesn't make sense because .val() is for form field values, not for getting table row/cell text. You need to use .text() to get the text of the individual cells, but do the showing and hiding at the row level. So maybe a little something like this:

var $rows = $('#table tr');
var $cells = $rows.find('td');

$('#search').keyup(function() {
  var searchText = this.value;
  $rows.hide();
  $cells.filter(function() {
    return $(this).text().indexOf(searchText) === 0;
  }).parent().show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="search" placeholder="Type to search" maxlength="10">
<table id="table">
  <tr>
    <td>3123124</td>
    <td>438785345</td>
  </tr>
  <tr>
    <td>123131234</td>
    <td>31234144</td>
  </tr>
  <tr>
    <td>8909808</td>
    <td>8709090980</td>
  </tr>
</table>

"how do I also make regex accept only 10 characters?"

I don't really see any reason to limit the search term to only 10 characters, but if you want to do that the simplest way is just to add a maxlength="10" attribute on the input element.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Hi would like to thank you for your answer. What does the `this` mean? – Ong Kong Tat Jul 14 '17 at 05:08
  • By any chance, are you willing to take a look at my code because I can't seem to get it to work although it works perfectly on a normal table – Ong Kong Tat Jul 14 '17 at 06:46
  • In generic terms, within a function `this` refers to the object the function was called on. In the case of most jQuery code, `this` will refer to the current element. So on the first line of the keyep handler `this` is the search input element. Within the `.filter()` function that code is called once per TD element and `this` refers to the current TD. – nnnnnn Jul 14 '17 at 07:09
  • If the code I've shown doesn't work for your table that's probably because I forgot to allow for your table being loaded by Ajax. Try moving the $rows and $cells declarations and assignments inside the keyup event handler. – nnnnnn Jul 14 '17 at 07:13
  • Thank you so much! I followed your idea and it worked! Really helpful. By the way, just wanted to know is it possible to search using a specific column only instead of all the columns? – Ong Kong Tat Jul 14 '17 at 07:23
  • Sure. Just change `.find('td')` to `.find('td:nth-child(1)')` to only search the first column. Make it `2` instead of `1` to search the second column. Etc. – nnnnnn Jul 14 '17 at 07:38