Extra parameters using Autocomplete like Google jQuery Plugin - javascript

I cant figure out this
Im using the plugin from http://xdsoft.net/jqplugins/autocomplete/. I need to send an extra parameter to the server to display the colony according to the zipcode for filtering. But I'm not able to get the value. My source code is as follows:
$('#colony').autocomplete({
source: [
{
url: "PROV_getColony.ashx?q=%QUERY%" + "&zipCode=" +
$("#zipcode").val(),
type: 'remote',
minLength: 2
}
]
});
$("#zipcode").val() is always empty. If I use an alert outside the function, then the value is returned though.
What am I missing?

Based on the documentation you can use the replace option method (xdsoft.net/jqplugins/autocomplete/#replace) to modify the URL before it is being sent:
$('#colony').autocomplete({
source: [
{
url: "PROV_getColony.ashx?q=%QUERY%" + "&zipCode=%ZIPCODE%"
type: 'remote',
minLength: 2
}
],
replace: function( url,query ){
return url.replace('%QUERY%', encodeURIComponent(query)).replace('%ZIPCODE%', $("#zipcode").val());
}
});

Related

Trying to fill select box with Inputpicker plugin and JQuery

$('#src_prodline').inputpicker({ calling the plugin function
fields:['id','code','description'],
fieldText : 'description',
fieldValue : 'code',
headShow: true,
filterOpen: true,
$.ajax({
url: 'item_action.php', //Calling the function
type:"POST",
data: {
btn_action:'src_prodline' //Set item_id and variable se
}
});
});
In my console I got this error:
SintaxError: missing : after property id
What's wrong with that and how can I fix it???
UPDATE:
Creating a new php file it's working
$('#src_prodline').inputpicker({
fields:['id','code','desc'],
fieldText : 'description',
fieldValue : 'code',
pagination: true,
limit: 5,
headShow: true,
filterOpen: true,
url: 'item_1.php',
pageCurrent: 1
});
BUT unfortunately this is not what I want because I got a PHP page with different functions and I call one of theme with a $_POST['btn_action']
Example:
if ($_POST['btn_action']=='src_prodline'){
...........
}
So, my problem is that I don't have idea how can I send this variable at PHP page without error.
-->LOOK the code above update<--
Do you have any idea how can I solve this?
UPDATE Ver. 2.0
I fixed it adding the variable in the web address but I hate to do that:
url: 'item_action.php?r=src_prodline'
Now, it's working but if somebody has a better solution please let me know it.

update parameters variable on change.search using bootgrid with structured-filter

I am using https://github.com/evoluteur/structured-filter and http://www.jquery-bootgrid.com/ to create an advanced search through ajax/php.
Initially the code works and returns the data from the php file, but when trying to use structured-filter to pass $_GET variables to the php file through the use of jquery-bootgrid I am struggling.
No matter what I try, the url it is posting to has no $_GET variables, I have tried $("#grid-data").bootgrid("reload"); but nothing changes.
It appears the params variable is just not updating.
Here is my jquery script in full:
<script type="text/javascript">
$(document).ready(function() {
$("#myFilter").structFilter({
fields: [{
type: "text",
id: "gamertag",
label: "Gamertag"
}, {
type: "text",
id: "name",
label: "Team Name"
}, {
type: "number",
id: "wagePerMatch",
label: "Wage Per Match"
}, {
type: "number",
id: "gamesRemaining",
label: "Contract Games Remanining"
}, {
type: "boolean",
id: "transferListed",
label: "Transfer Listed"
}
]
});
var params = "";
$("#myFilter").on("change.search", function(event) {
var params = $("#myFilter").structFilter("valUrl");
$("#grid-data").bootgrid("reload");
console.log(params); // works, returns params
});
$("#grid-data").bootgrid({
ajax: true,
url: function() {
return "/api/search.php?" + params; // params never updates?
}
});
});
</script>
Is there a way to update params in .bootgrid when it changes in $("#myFilter").on("change.search" as right now its only sending requests to /api/search.php? (missing the parameters)
Now i don't have to much reputation, i am unable to add comment on this,
Please check this below URL, hope this will help you
http://www.jquery-bootgrid.com/Documentation#events
if you are looking for append the rows in existing grid so you can use "append" as given in URL or if you want to update the whole table you can destory the table and re-create a "bootgrid" object with binding with the respective DOM id's

Selectize.js get more data in "onItemAdd" callback

TL;DR
To make it clearer, I want to have access to ALL the data in the selected JSON object inside the onItemAdd function. Right now I only have access to _id and name via the config variables.
Ok, so I have a working Selectize.js function grabbing a JSON object from my server and creating the select options.
What I want to know is, can I get anymore data from the existing JSON object inside the "onItemSelect" callback?
The only data I can get directly is the value as specified in the config, which in this case is the "_id" and the $item which i assume is form the labelField in the config, in this case is the name form the JSON data.
How can I get more data than that for the selected item? You see in the render object I use the variable item.sku, how can I access the sku variable in the "onItemAdd" callback?
the data form the server is a json array:
[
{ _id: 'abcd1234', name: 'Sample', sku: '00123' },
{ _id: 'efgh5678', name: 'Sample2', sku: '00124' }
]
My function
// setup select box to add new products to list
$('#buyingGroupAddProducts').selectize({
valueField: '_id',
labelField: 'name',
searchField: 'name',
options: [],
create: false,
closeAfterSelect: true,
render: {
option: function(item, escape) {
return '<div>'+ escape(item.sku) + ': ' + escape(item.name) + '</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/buying/products-search',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
onItemAdd: function(value, $item) {
// DO the thing
console.log($item);
}
});
SelectizeJS site: http://selectize.github.io/selectize.js/
a hack to solve your problem : inside onItemAdd function you can access all your JSON : this.options gives you all the selectize options, so now you have the value and the complete JSON, you can easily find back the item in your json that corresponds to the value selected. I can complete my answer if you provide a use case in plunker.

Populate a Select2 Tag input field with data from an AJAX request using X-editable jQuery library

I am in desperate need of some help from JavaScript experts. I have spent the last 7 hours trying hundreds of combinations of code to get a basic Tag selection input field to work with the library x-editable and select2.
I am building a Project Management app which is going to have Project Task data shown in a popup Modal Div. In the Task Modal, all Task fields will be editable with in-line edit-in-place capability using AJAX.
I am using:
the jQuery edit in place library called X-Editable - http://vitalets.github.io/x-editable/
The drop down selection jQuery library Select2 - https://select2.github.io/
The jQuery MockAjax library to allow simulating AJAX request responses. https://github.com/jakerella/jquery-mockjax
I have setup a basic JSFiddle demo to experiment with just for this StackOverflow question. I don't have the thousands of lines of code from my actual application , however I do have majority of the 3rd part libraries that are being used included into the page. THe reason is to make sure that none of them are interfering with the results.
JSFiddle Demo: http://jsfiddle.net/jasondavis/Lusbqfhs/
The Goal:
Setup X-editable and Select2 on a Field to allow users to select and enter in Tags for a Project Task.
Fetch available Tag records from a backend server which will return a JSON response with Tag ID number and Tag Name and use this data to populate the Selection2 input field to allow a user to select multiple Tags.
Allow user to also type in a NEW tag and it will post and save the new Tags to the backend as well!
When tags are selected and the save button is clicked, it will save the list of selected Tags bu ID number back to a database.
Problems:
Now I have tried hundreds of variations of options and code combinations from my research in the past 7 hours. I cannot seem to get this basic functionality to work and majority of the examples I have found do not seem to work correctly anymore!
On this demo page for the library x-editable http://vitalets.github.io/x-editable/demo-plain.html?c=inline near the bottom of the examples in the table where it says Select2 (tags mode) that functionality is what I need! I just need it to load the available tags from an AJAX request and all the docs claim it can do this with no problem at all!
This is the Documentation section from X-Editable for Select2 fields - http://vitalets.github.io/x-editable/docs.html#select2
It also links to the Select2 documentation and claims that all the Options in Select2 can be set and used as well located here - https://select2.github.io/options.html
I use MockAjax library to simulate an AJAX response in pages like JSFiddle for testing. In my JSFiddle demo here http://jsfiddle.net/jasondavis/Lusbqfhs/ I have 2 MockAjax responses set up....
$.mockjax({
url: '/getTaskTags',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
$.mockjax({
url: '/getTaskTagById',
responseTime: 400,
response: function(settings) {
this.responseText = [
{id: 1, text: 'user1'},
{id: 2, text: 'user2'},
{id: 3, text: 'user3'},
{id: 4, text: 'user4'},
{id: 5, text: 'user5'},
{id: 6, text: 'user6'}
];
}
});
They both are supposed to return a Mock JSON string for my Selection list to be populated with.
Here is my code for the demo...
$(function(){
//remote source (advanced)
$('#task-tags').editable({
mode: 'inline',
select2: {
width: '192px',
placeholder: 'Select Country',
allowClear: true,
//minimumInputLength: 1,
id: function (item) {
return item.CountryId;
},
// Get list of Tags from AJAX request
ajax: {
url: '/getTaskTags',
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (item) {
return item.TagName;
},
formatSelection: function (item) {
return item.TagName;
},
initSelection: function (element, callback) {
return $.get('/getTaskTagById', {
query: element.val()
}, function (data) {
callback(data);
});
}
}
});
});
Now in the demo when you click the field to select Tags, it just keeps "loading" and never gets a result. Looking at the Console, it seems my MockAjax request is not working, however the 2nd one is working so I am not sure what is wrong with my AJAX request?
I could really use some help if someone can help to get this to work I would be very greatful, I have spent my whole night without sleep and am not even any closer to a working solution! Please help me!
Thank you
X-Editable uses Select2 3.5.2 which doesn't use jQuery.ajax() directly. It has its own ajax function and calls jQuery.ajax() like that:
transport = options.transport || $.fn.select2.ajaxDefaults.transport
...
handler = transport.call(self, params);
That's why $.mockjax({url: '/getTaskTags'... does not work.
To get it work you need to create your own transport function, something like that:
var transport = function (queryParams) {
return $.ajax(queryParams);
};
and set the transport option:
ajax: {
url: '/getTaskTags',
=> transport: transport,
type: 'post',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},

How can I autoselect the first option in Twitter typeahead.js

Please note that this is for Twitter typeahead.js which is not the same as boostrap typeahead (which has been removed from Bootstrap in 3.0)
According to this issue on Github the feature has been added, but I can not see how to implement it.
I have tried
autoselect: 'first'
and
autoselect: true
Neither seems to work.
Make sure you're using the latest release (>v0.10.0). This feature was merged into the master branch on Feb 2, 2014. Here's how you would initialize a typeahead with the autoselect: true option:
$('.typeahead').typeahead({
autoselect: true
},
{
name: 'my-dataset',
source: mySource
});
For more, check out the documentation on initializing the typeahead and the autoselect option.
There is an autoSelect option that about to be merged to master. You can clone the requester's repo and use it immediately (working great for me).
https://github.com/twitter/typeahead.js/pull/1356
https://github.com/hongz1/typeahead.js
I honestly couldn't make autoselect option work, besides I needed to implement it in a way that it autoselects the first option ONLY IF I HAD ONE RESULT from the source.
This worked for me:
...
success: function(data) {
process(data);
if (data[0] != null) {
$(".tt-dropdown-menu .tt-suggestion").trigger("click"); //autoselect the first element.
}
}
...
I used a dirty trick, I just added empty element as First Item, works like a charm...
var typeaheadSource = [{ id: 0, firstName: " | | "}, <?php print $product_list; ?>];
Which look like this...
var typeaheadSource = [{ id: 0, firstName: " | | "}, { id: 1, firstName: "Coca Cola 1.5L | 9555589200415 | 0.00"}];
In my case I'm populating the data in PHP.
You may wanna do some checking in the onSelect event, if it requires in your case.
Hope this helps.
Tested on version 0.11.1 for ajax requests to autoselect the first option, only when 1 result is returned
The code hooks the return from the ajax request, if the return is only 1 item it will tell the typeahead the request failed ( preventing the list from opening ) and manually set the result
const $field = $( '#auto_complete' );
const bloodhound = new Bloodhound( {
datumTokenizer: Bloodhound.tokenizers.whitespace,
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: `remoteUrl?&q=%QUERY`, // Set the proper URL...
wildcard: '%QUERY',
rateLimitWait: 500,
cache: false,
transport: ( settings, onSuccess, onError ) =>
{
return $.ajax( settings )
.done( ( data, textStatus, jqXHR ) =>
{
if ( data.length === 1 )
{
onError( jqXHR, 'abort', '' ); // Pretend the request failed
$field.val( data[0].code ) // Set the value in the input, don't use $field.typeahead('val', results[0].code);
$field.blur();
$field.trigger( 'typeahead:select', [ data[0] ] ); // Simulate the user selecting the option
return;
}
onSuccess( data, textStatus, jqXHR );
} )
.fail( onError );
}
}
} );
$field.typeahead(
{ /* .. options...*/ },
{
source: bloodhound,
}
);

Categories