How would I crop a tab to a jQuery autocomplete window?

Is there a way to trim (remove leading / trailing spaces) user input in a text box <input>for jQuery autocomplete before matching with a list of names: values? I currently have a text box in which users must enter names. The names are then mapped to a list of name pairs: value by jQuery:

<script type="text/javascript">

var resources = [
               <?php 
                    foreach($data['Resource'] as &$row){
                        $Name = $row['Forename']." ".$row['Surname'];  
                        echo "{";
                        echo "  label:'$Name',";
                        echo "  value:'$row[EmployeeNumber]'";
                        echo "},";
                    }
                 ?>
                ];

    jQuery(function(){
        jQuery('#Resource').autocomplete({
            source: resources,
            focus: function(event, ui) {
                jQuery('#Resource').val(ui.item.label);
                return false;
            },          
            select: function(event, ui) {
                jQuery('#Resource').val(ui.item.label);
                jQuery('#EmployeeNumber').val(ui.item.value);
                return false;
            }
        });
    }); 
</script>

My problem is that if the user enters a name that matches one in the map resources, but with spaces after it, it will not be matched, and therefore no value will be assigned to this value. I would like at least (if there were also no leading spaces) for trailing spaces to be ignored on this map.

, , ?

EDIT:

, , , -, ? .

+2
2

source, , :

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 );
  }));
}

. $.trim(), , $.grep(), / .


, "No Result..." , :

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: '' }]);
}
+5

jQuery.trim:

jQuery.trim(yourValue);
+1

Source: https://habr.com/ru/post/1756178/


All Articles