Is there any way to trim (remove leading/trailing spaces) the input entered by a user into a jQuery auto-completing text <input>
box before it is matched against the list of names:values? I currently have a textbox in which users are meant to enter names. The names are then matched against a list of name:value pairs 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 resources
map, but with spaces after it, it won't be matched and thus no value will be assigned to the input. I would like for trailing spaces at least (if not also leading spaces) to be ignored on this mapping if possible.
Additionally, would it be possible to add a default value for the input box if no map is found?
EDIT:
As an aside, is it possible to have a no-match entry shown in the drop-down autocomplete box if the user types something that doesn't match? Apologies for the after-question edit.
Use
jQuery.trim
:You can do the find yourself in the
source
function, instead of using the built-in function, like this: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: