Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead.js pass dynamic additional parameters

Suppose I have a form with multiple fields using typeahead.js, for some fileds I wish to pass values from previously populated form fields as part of the query. For example

<input id="First_Name" type="text">
<input id="Last_Name" type="text">

JavaScript:

$('#Last_Name').typeahead({
  name: 'typeahead',
  remote: 'Search.pl?query=%QUERY'.
  template:[
 ......
  ].join(''),
  engine: Hogan
});

Since I have multiple input boxes, some should pass the ID & value of other input boxes as part of the remote query, I wonder if there is a generic way to append the ID & value to this string only if the fields contain values.

Thanks in advance

like image 738
Dr.Avalanche Avatar asked Oct 15 '13 10:10

Dr.Avalanche


2 Answers

You can do that. Use a replace to process the query string before it is set.

Something like:

$('#Last_Name').typeahead({
  name: 'typeahead',
  remote: {
    url: 'Search.pl?query=%QUERY',
    replace: function(url, uriEncodedQuery) {
      val = $('#First_Name').val();
      if (!val) return url;
      //correction here
      return url + '&first_name=' + encodeURIComponent(val)
    },
  template: ...,
  engine: Hogan
});
like image 63
Nitzan Shaked Avatar answered Sep 28 '22 08:09

Nitzan Shaked


Old topic but can be usefull with a more detailed answer :

As @Shaked has already said, you need to use replace function

1 . If you wan to have dynamic parameters

This is the case, you wan't dynamic parameters that not be part of typehead input.

This case is not the recommanded one, bacause if you are in this situation you shouldn't need typehead.

$('#myID').typeahead({
  name: 'typeahead',
  remote: {
    url: 'search.php',
    replace: function(url, uriEncodedQuery) {
      val = $('#yourValue').val();
      if (!val) return url;
      return url + '?param=' + encodeURIComponent(val)
    },
  template: ...,
});

2 . If you want to add dynamic parameters

This case is the more interesting one. Someting you wan't to get some additionnal parameters comming from other DOM inputs that they do not part of Typehead input.

You need to use replace too but the content is different :

 $('#myID').typeahead({
      name: 'typeahead',
      remote: {
        wildcard: '%QUERY',
        url: 'search.php?query=%QUERY',
        replace: function(url, uriEncodedQuery) {
          val = $('#yourValue').val();
          if (!val) return url.replace("%QUERY",uriEncodedQuery);
          return url.replace("%QUERY",uriEncodedQuery) + '&param=' + encodeURIComponent(val)
        },
      template: ...,
    });

With this code, you will be able to get TypeHead input + some additional parameters

like image 21
OrcusZ Avatar answered Sep 28 '22 08:09

OrcusZ