wormyworm
wormyworm

Reputation: 179

Always show a string in jQuery Autocomplete even if it doesn't match input string

I'm aware of the same question posted at: Always show a specific choice in jQuery Autocomplete even if it doesn't match input

The problem is when using the open function as suggested as a solution in the above question, the event is only triggered when there is a matching item within the autocomplete list. Therefore, the specific choice is not always shown when the user is typing in search box.

https://jsfiddle.net/u1jwz6s4/

<html lang="en">
<head>
<meta charset="utf-8">
<title>autocomplete demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>

<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

</body>
</html>

$( "#autocomplete" ).autocomplete({
source: [ "c++", "java", "php", "coldfusion", "javascript", "asp",    "ruby" ],
open: function(){
$('.ui-autocomplete').prepend("search by keyword")
},
});

I want to display "search as keyword" as an option at the very top always, whether there is a matching string or not while user is typing in search box. Currently, "search as keyword" is only displayed at top when a matching string is found. Also, is there anyway to make "search as keyword" a clickable event within the search form? See the jsfiddle to see what I'm describing.

Upvotes: 3

Views: 948

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370809

You can use a response option to unshift the search by keyword string to the array of displayed labels:

const $input = $("#autocomplete");
$input.autocomplete({
  source: ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"],
  response: (event, ui) => {
    const label = 'search by keyword';
    ui.content.unshift({
      label,
      value: $input.val()
    });
  }
});
$(document).on('click', '.ui-autocomplete div:contains("search by keyword")', () => {
  console.log('searching for ' + $input.val());
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<label for="autocomplete">Select a programming language: </label>
<input id="autocomplete">

Upvotes: 2

Related Questions