Trim Search Input

Occasionally a user when inputting search criteria in a tables search field will place a space after the data which in turn will result in a “No Records Found” message.

Is there script that will not look at the trailing spaces after the inputted search criteria?

Example: User enters “1234” OR "1234 " and either entry will return data containing “1234”

Any and all help would be appreciated… JON

I’d like to know of a solution to this “issue” too.

Here is a solution that was provided to me by Stephen Chapman:

$(document).on('knack-view-render.any', function(event, view, data) {
  
  $('input[type="text"], textarea').on('blur', function() {
        // Get the trimmed value of the input
        var trimmedValue = $(this).val().trim();
        
        // Update the input with the trimmed value
        $(this).val(trimmedValue);
    });

});

Hey @Jon,
Thanks for the mention! Just note that the above code only works in scenarios where you input the text in the search input and then press the Search button separately.

This will not work if you input the text in the search input and press the Enter key, as the input field never loses focus and never triggers the event handler.

You would need a similar event handler that listens for the Enter key being pressed while the input is focused.
This updated code should handle both scenarios, with a shared function:

$(document).on('knack-view-render.any', function(event, view, data) {
  
  // Event handler for blur on input and textarea elements
  $('input[type="text"], textarea').on('blur', function() {
    trimAndUpdateInput($(this)); // Pass $(this) as an argument
  });

  // Event handler for Enter key press on input elements
  $('input[type="text"]').on('keypress', function(event) {
    if (event.keyCode === 13) {
      trimAndUpdateInput($(this)); // Pass $(this) as an argument
    }
  });

});

// Function to trim and update the input value
function trimAndUpdateInput(inputElement) {
  
  var trimmedValue = inputElement.val().trim();
  inputElement.val(trimmedValue);

}

Hey Stephen, thank you for the revised code. Works as expected… JON

Hey Stephen, thank you for the revised code. Works as expected… JON