How would I trim the input to a JQuery auto-complete box?

后端 未结 2 2035
孤城傲影
孤城傲影 2021-01-15 01:39

Is there any way to trim (remove leading/trailing spaces) the input entered by a user into a jQuery auto-completing text box before it is matched

相关标签:
2条回答
  • 2021-01-15 02:18

    Use jQuery.trim:

    jQuery.trim(yourValue);
    
    0 讨论(0)
  • 2021-01-15 02:24

    You can do the find yourself in the source function, instead of using the built-in function, like this:

    source: function( request, response ) {
      var matcher = new RegExp($.trim(request.term).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
      response($.grep(resources, function(value) {
        return matcher.test( value.label || value.value || value );
      }));
    }
    

    You can try a demo here. This uses $.trim() to trim down the search term before it gets passed into $.grep() to get the leading/trailing white-space ignorant effect you want.


    For your edit, you can do this, but the "No Result..." will be selectable, give it a try here:

    source: function( request, response ) {
      var matcher = new RegExp($.trim(request.term).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i" );
      var matches = $.grep(resources, function(value) {
        return matcher.test( value.label || value.value || value );
      });
      response(matches.length ? matches : [{ label: 'No Result Found', value: '' }]);
    }
    
    0 讨论(0)
提交回复
热议问题