skip to Main Content

I have the following jQuery that runs as a user types in an input box.

var $rows = $('#table tbody tr');
$('#search').keyup(function() {
  var val = '^(?=.*\b' + $.trim($(this).val()).split(/s+/).join('\b)(?=.*\b') + ').*$',
    reg = RegExp(val, 'i'),
    text;

  $rows.show().filter(function() {
    text = $(this).text().replace(/s+/g, ' ');
    return !reg.test(text);
  }).hide();
});

How do I get the same jQuery to run if there’s already text in the input box on page load?

3

Answers


  1. You can use ready function and check if textbox has text in it.

    $(document).ready(function(){
      if ($("#search").val() !== "") {
        // your code here.
      }
    });
    
    Login or Signup to reply.
  2. Just move all the logic into its own named function:

    function doFilter() {
      var $input = $('#search'),
        val = '^(?=.*\b' + $.trim($input.val()).split(/s+/).join('\b)(?=.*\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;
    
      $('#table tbody tr').show().filter(function() {
        text = $(this).text().replace(/s+/g, ' ');
        return !reg.test(text);
      }).hide();
    }
    
    $(function() {
      $('#search').on('keyup', doFilter); // Add it as a listener
    
      doFilter(); // Call it upon initialization
    });
    Login or Signup to reply.
  3. You should move the logic into its own function but you can just trigger the keyup event if you don’t want to refactor what you have.

    $(function() {
      $('#search').keyup(function() {
        //your existing code
        console.log($(this).val());
      }).trigger("keyup");
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input id="search" value="abc" />
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search