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
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
});
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) + '¶m=' + encodeURIComponent(val)
},
template: ...,
});
With this code, you will be able to get TypeHead input + some additional parameters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With