Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multiple autocomplete in an input field based on a sentence structure?

The sentence structure of my autocomplete is:

<Occupation> <for> <time period>

Example:

  • Student for 5 years
  • Teacher for 2 years

In the database, I have a column containing a list of occupations. With jQuery UI autocomplete, I populate the first two sections in the text input using the following codes:

<script>
    $(function() {
        $("#occupation").autocomplete({
            source: 'search.php',
            delay: 500,
            select: function(event, ui) {
                $(this).val(ui.item.value)
            }
        });
    });
</script>
<input type='text' name='occupation' id='occupation’>

The search.php code:

<?php
$searchTerm = $_GET['term'];
$query = $db->query("SELECT DISTINCT occupation FROM table WHERE occupation LIKE '%" . $searchTerm . "%' ORDER BY occupation ASC");
$a_json = array();

while ($row = $query->fetch_assoc())
    {
    $data_row["value"] = $row['occupation'] . ' for';
    $data_row["label"] = $row['occupation'];
    array_push($a_json, $data_row);
    }

echo json_encode($a_json);

Now, is there any way to create a second trigger to make an autocomplete for the rest? Like after selecting an occupation, if the user inputs 5, it’ll show the following autocomplete options for the time period: 5 days/ 5 weeks/ 5 months/ 5 years. Like the image below: Example

Thanks in advance for your suggestions.

like image 716
Ashonko Avatar asked Nov 28 '17 12:11

Ashonko


People also ask

Which attribute is used to provide an autocomplete feature for text field?

The autocomplete attribute specifies whether a form or an input field should have autocomplete on or off. Autocomplete allows the browser to predict the value. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values.

How do you show the suggestion list in the input field?

Approach: Create a div with the class as a container. Inside of this div, create another div with a class as a text-container that will contain the <input> tag & <datalist> tag. Declare the list attribute as programmingLanguages inside the <input> tag.

How do I make an autocomplete drop down list in HTML?

You can try HTML <datalist> tag for autocomplete dropdown.


1 Answers

I would advise following the Multiple example shown here: http://jqueryui.com/autocomplete/#multiple

Basically, we're going to selectively pick out tags to fill in, using " for" as your delimiter instead of ",".

var occupations = [{
  value: "Assistant for",
  label: "Assistant"
}, {
  value: "Student for",
  label: "Student"
}, {
  value: "Teacher for",
  label: "Teacher"
}];

var oLength = [
  "Days",
  "Weeks",
  "Months",
  "Years"
];

$(function() {
  function split(val) {
    return val.split(/\sfor/);
  }

  function extractLast(term) {
    return split(term).pop();
  }

  $("#occupation").on("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB &&
      $(this).autocomplete("instance").menu.active) {
      event.preventDefault();
    }
  }).autocomplete({
    minLength: 0,
    source: function(request, response) {
      var term = extractLast(request.term);
      var results = [];
      if (request.term.indexOf("for") > 0) {
        var regE = /^(.*)\sfor\s(\d)\s(.*)$/
        if (regE.test(request.term)) {
          return false;
        }
        if (parseInt(term) > 0) {
          $.each(oLength, function(k, v) {
            results.push(term + " " + v);
          });
        }
      } else {
        results = $.ui.autocomplete.filter(
          occupations, request.term);
      }
      response(results);
    },
    focus: function() {
      // prevent value inserted on focus
      return false;
    },
    select: function(event, ui) {
      var terms = split(this.value);
      terms[0] = terms[0] + " for";
      // remove the current input
      terms.pop();
      // add the selected item
      terms.push(ui.item.value);
      // add placeholder to get the comma-and-space at the end
      terms.push("");
      this.value = terms.join("");
      return false;
    }
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input type="text" id="occupation" />
like image 51
Twisty Avatar answered Oct 18 '22 18:10

Twisty