I'm using jquery-ui to create a search dropdown, but I'd like to replace underscores with spaces in the dropdown results. I've tried .replace on the source but it doesn't seem to work.
Below is my autocomplete code. How do I use .replace(/_/g, " ")
on it?
Thank you.
$(document).ready(function(){
var alls = $.each([
'Dr._Peppins',
'Spain',
'index',
],
$( "#userInput" ).autocomplete({
source: alls
});
});
CodePudding user response:
Consider the following.
$(function() {
var alls = [
'Dr._Peppins',
'Spain',
'index',
];
function undScore2Space(word) {
return word.replace("_", " ");
}
function filterArray(arr) {
$.each(arr, function(i, e) {
arr[i] = undScore2Space(e);
});
return arr;
}
$("#userInput").autocomplete({
source: function(req, resp) {
var results = $.ui.autocomplete.filter(alls, req.term);
resp(filterArray(results));
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
<div >
<label for="userInput">Input: </label>
<input id="userInput">
</div>
In your example, you perform an Each. This is not properly formed and should generate an error.
In the case of an array, the callback is passed an array
index
and a corresponding arrayvalue
each time. (The value can also be accessed through thethis
keyword, but Javascript will always wrap thethis
value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
So you do not want to initialize Autocomplete on each item in the array. You can modify each part if you choose, yet if you expect the source to contain these characters, it would be best to filter them out after the lookup.
You can make use of a function for source
and perform events this way.
You can also do the following:
$(document).ready(function(){
var alls = [];
$.each([
'Dr._Peppins',
'Spain',
'index'
], function(index, elem){
alls.push(elem.replace("_", " "));
});
$("#userInput").autocomplete({
source: alls
});
});
CodePudding user response:
Try this:
source: alls.replace("_", " ");