kendoAutoComplete for multiple dataTextField - php

The code below works for autocomplete for FileNo (field) only. i want this function to work for other attributes of employee too. i.e FirstName, LastName
dataTextField: "FileNo" <---------------- here dataTextField gets sing field. how could it be for multiple fields?

Since you are the one that knows on which columns want to search, my recommendation is:
Implement index.php/hr_management/manage_hr/search_employee/ in such way that is able to do the search for any of the columns that you want (FileNo, FirstName, LastName...).
This service will return three columns (at least) providing an id, column name on which you found the match and match value.
match value is used for displaying values in the autocomplete.
Once selected value on autocomplete use the column name and match value for filtering on the grid.

You should use template to change what is displayed in the dropdownlist of the autocomplete. Then the dataTextField will only be used inside the input element.
Here is how it goes to create template.

Kendo Autocomplete has dataTextField that accepts a field name(e.g. employeeID, employeeName etc. of a datasource ) to use for filtering items.
To use multiple fields, you have to set one of the fields to hold concatenated fields during parsing of datasource in your schema as given below.
Then set your filter of AutoComplete to "contains"
I did it as follows.
var myDataSrc = new kendo.data.DataSource({
transport: {
read: {
type:"GET",
url:clientDataURL,
dataType: "jsonp",
contentType: "application/json",
}
},
schema: {
parse: function(clntDB) {
$.each(clntDB, function(ky, clnt) {
clnt.firstName = clnt.clientUID + " | " + clnt.firstName+ " " + clnt.lastName;
});
return clntDB;
}
},
pageSize: 4 // Number of Items to show during input
});
/// See the firstName above it's reconstructed to hold concatenated lastname , ID and firstname string.
Next step is to use parsed firstName as a value of dataTextField of kendo Autocomplete.
Then
var selectedClntID; //// Actually, this aims at getting the ID for future use
$("#YOURSEARCHINPUTID").kendoAutoComplete({
dataSource: myDataSrc ,
template: tmplSrchdClnt, // YOUR TEMPLATE like "<div>firstName</div>"
dataTextField:"firstName",
filter:"contains", /// DON'T FORGET TO ADD THIS
minLength : 1 ,
select: function(e) {
var selectedClnt = this.dataItem(e.item.index()),
x = kendo.stringify(selectedClnt);
selectedClntID = JSON.parse(x);
}
// headerTemplate: '<div><h2>ID - LastName</h2></div>'
});
However, tough to find resource indicating like this, it's awesome when you see it working.This is engine of my project when it comes to autocompletion. I did it this way.
Alternatively, you can convert to
data = new Employee(firstname, lastname, ID); // on client side
function Employee( firstname, lastname, ID ){
this.filterStr = firstname + ""+lastname+" "+ID;
}
give data to kendo AutoComplete dataSource and use filterStr as dataTextField.

Another code example adding a new field to the datacourse to use as dataTextField.
// Build our data source object.
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: readUrl,
}
},
group: {field: "region"},
schema: {
data: function(response) {
$.each(response, function(k, v) {
response[k].searchString = v.airport + " " + v.iataCode;
});
return response;
}
}
});
$(selector).kendoAutoComplete({
dataTextField: "searchString",
filter: "contains",
template: '<span class="k-state-default">#: data.airport # (#: data.iataCode #)</span>',
height: 400,
dataSource: dataSource,
});

Related

Jquery auto complete results appear as individual letters, not words

I'm using jquery to capture a users input in a text field and then display a dropdown of possible options.
The script calls a php page which searches and returns the results to the ajax request.
Where there are multiple values returned by PHP they appear like
["Site 4,"Site 2","Site 1","Site 6","Site 7","Site 0"]
A single value would appear like
["Site 4"]
What I get in my drop down is as follows (based on the single entry)
[
LINE
"
S
i
t
e
LINE
4
"
]
Where LINE is a separator between Site & 4 and the quotes and brackets are shown.
My Jquery is:
$('#site').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'siteCheck.php?name=' + request.term,
success: function( data ) {
console.log (data)
response( $.map( data, function( item ) {
return {
label: item,
value: item,
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
$('#site').val(ui);
}
});
How do I get this to return the dropdown list as
Site 4
Site 2
Site 1
Site 6
Site 7
Site 0
and not individual letters !
Thanks
First of all: Is it a typo, that your json array has no closing " for the first element?
Second: according to the doc for autocomplete, source, would be sufficient to just pass the array as simple array, as you have it already. No need to transform it to something with label/value.
In the example of remote datasource, they just adding source: 'remoteScript.php'
So you could just use
$( '#site' ).autocomplete({
source: 'siteCheck.php?name=' + request.term,
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
$('#site').val(ui);
}
});
EDIT:
Try to modify you server side script to accept term as GET parameter, then your URL can drop the part, with term added, as the autocomplete does it for you:
source: 'siteCheck.php', //should accept term as parameter

JQuery PHP AJAX filter based on multiple checkbox array

I'm hoping someone can point me in the right direction. I'm primarily a PHP developer but I'm really trying to get my head around jquery and javascript more due to the increasing number of AJAX work requests we receive.
Basically I have a sidebar filter that works fine. It is based on 3 things. A group, category and sub category. So for example, Boots as the category, Leather (type) as a sub category and Black (colour) as tertiary filter. At the moment it works based on a GET form. However I want to use live filters instead so as they click a checkbox, it updates the results based on a query. I can write all the PHP for this but I'm struggling to get the data together by jQuery. I've looked at using jQuery .each and .change.
There are 3 groups of checkboxes and they are all based on arrays. So for example again: category[], subcategory[], tertiary[].
Thanks in advance for the help.
Some example HTML
<input id="$ProdCatLabel" class="side_filter_checkbox" name="ProdCatFil[]" type="checkbox" value="$ProdCat">
<input id="$ProdSubCatLabel" class="side_filter_checkbox" name="ProdSubCatFil[]" type="checkbox" value="$ProdSubCat">
<input id="$BrandingLabel" class="side_filter_checkbox" name="BrandFil[]" type="checkbox" value="$Branding">
My attempts:
var prodcats = $('side_filter_prodcats[name="ProdCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
var prodsubcats = $('side_filter_prodsubcats[name="ProdSubCatFil[]"]:checked')
.map(function() { return $(this).val() })
.get()
.join(",");
$.ajax({
type: "POST",
url: "[ENTER PHP URL HERE]",
data: "ProdCats=" + prodcats + "ProdSubCats=" + prodsubcats,
success: function(msg) { $(".content_area").html(msg); }
});
Am I barking up the right tree here?
Ok let's say your checkboxes have the classes category, subcategory and tertiary. You could attach a click event handler to each group that calls the function to load in the correct data, passing the checkbox value and a class or data-attribute to the function as parameters.
// Your main DOM ready function
$(document).ready(function() {
// Checkboxes click function
$('input[type="checkbox"]').on('click',function(){
// Here we check which boxes in the same group have been selected
// Get the current group from the class
var group = $(this).attr("class");
var checked = [];
// Loop through the checked checkboxes in the same group
// and add their values to an array
$('input[type="checkbox"].' + group + ':checked').each(function(){
checked.push($(this).val());
});
refreshData(checked, group);
});
function refreshData($values, $group){
// Your $values variable is the array of checkbox values
// ie. "boot", "shoe" etc
// Your $group variable is the checkbox group
// ie. "category" or "subcategory" etc.
// Now we can perform an ajax call to post these variable to your php
// script and display the returned data
$.post("/path/to/data.php", { cats: $values, type: $group }, function(data){
// Maybe output the returned data to a div
$('div#result').html(data);
});
}
});
Here's an example of the checkbox click function in action: http://jsfiddle.net/F29Mv/1/

Dynamically change dropdowns via SQL and calculate sums?

I've got a row in a table with 3 fields laid out as so:
Job Pay Grade Cost
<Select> <Select> <Calculation>
I've got an SQL table with the information above in it, for example:
Job Pay Grade Cost
Techie 1 100
Techie 2 200
Engi 2 300
Engi 3 400
Engi 4 500
What I need to do is to be able to select a Job from the dropdown and then the Pay Grade select box will change depending on what matches that job in the SQL database. It will then show the cost which relates to the to selected.
How can I go about this as I am a little stuck
First create ajax request when a job title is selected. WIthin the success callback of the request will generate html for the options for pay grade select from JSON response from server
jQuery
$('select.jobTitle').change(function(){
var $titleSelect=$(this);
$.getJSON('processJobGrades.php', { jobTitle : $(this).val() }, function(response){
var gradesOptionsHtml='';
/* create options html from json response */
$.each( response, function(i, item){
gradesOptionsHtml+='<option value="'+item.grade+' data-cost="'+item.cost+'">'+item.grade+'</option>';
});
$titleSelect.parent().find('select.jobGrade').html(gradesOptionsHtml);
});
});
IN processJobGrades.php receive $_GET['jobTitle'] . Do DB lookup and create json to send back.
PHP
$outputArray=array();
/*in loop over DB data:*/
$outputArray[]= array( 'grade'=>$row['grade'], 'cost'=>$row['cost']);
/*Output final array as JSON*/
echo json_encode( $outputArray);
jQuery change handler for paygrade select to get cost
$('select.jobGrade').change(function(){
var cost=$(this).find(':selected').data('cost')
$(this).parent().find('input.jobCost').val( cost);
})
You need to post the select job via $.ajax and then in success function populate the dropdown list like this:
function selectHandler (event, ui)
{
var id = event.target.id;
$.ajax({
type: "POST",
url: "/php/get_quantity_type.php",
dataType:"json",
data: { ingridient : ui.item.value},
success: function(data){$("#"+id+"_t").empty(); $.each(data,function(index,value) {$("#"+id+"_t").append('<option value="' + value + '">' + value + '</option>');})}
});
}
This example takes a name of a material from select list posts it via $ajax() to a php script and writes it down to a new dropdown list which id is based on id that triggered the event. If you need the php code just ask:)
You bind your job list to the event handler above:
("#job_list").bind("select",selectHandler);
This code posts data to "/php/get_quantity_type.php", and passess the result to function declared in success attribute;

jQuery UI & PHP - Sending 'To' Column to PHP

I am using jQuery UIs Sortable to allow a user to move items from 4 columns as well as change the order of items within each column. I have the latter working without problem; updating the new order to the database.
But I'm not sure how to handle storing moving from Column A to Column B. Each unordered list has a unique ID so I'd like to send that information along; I just don't have a firm understanding of how to do this.
$("#list1, #list2, #list3, #list4").sortable({
connectWith: ".sort",
placeholder: "shadow",
dropOnEmpty: true,
opacity: 0.8,
cursor: 'move',
update: function() {
var order = $(this).sortable("serialize") + '&update=update';
$.post("/update.php", order, function(theResponse) {
$("#alert").html(theResponse);
$("#alert").slideDown('slow');
slideout();
});
}
});
I've found an answer to my own question. The answer is to pass the data to the PHP file in a slightly different manner that allows for a more robust amount of variables (rather than just serializing one set of information).
var item = ui.item;
var new_ul = item.parent();
var order = [];
container.children('li').each(function(i){
reorder[i] = $(this).attr('id');
});
$.ajax({
method:'post',
url: 'update.php',
data:{
'new_ul':container.attr('id'),
'item':item.attr('id'),
'order':order
}
});
Full credit for this solution goes to user 'Zehee' at CodeIgniter (Who I believe got the solution from 37signals) http://codeigniter.com/forums/viewthread/175134/#831756

Parsing a JSON object with jQuery and creating two drop down lists with that data

I am trying to dynamically create two drop down lists, one will be provinces, and the other will contain the cities of each province, so when a user chooses a province, the cities drop down will populate, I am using jQuery's $.ajax function to get the data from a database which then passes it back as JSON, here is what I have thus far,
jQuery:
$.getJSON("provinces.php", function(data){
//clean out the select list
$('#province').html('');
//run the loop to populate the province drop down list
$.each(data, function(i, json) {
var province = json.province;
var cities = json.cities;
$('#province').append(
$('<option></option>').html(province)
);
});
});
a snippit of the JSON:
[
{"province":"Eastern Cape","cities":"Mthatha,Njoli,Port Alfred,Port Elizabeth,Queenstown,Uitenhage"},
{"province":"Freestate","cities":"Thaba Nchu,Virginia,Welkom"}
]
I am populating the provinces drop down, but not the cities drop down.
I would like to hear from you guys what you think the best method will be to achieve the cities drop down.
Store the json somewhere, i.e. using $('…').data(key, value).
Add a trigger for the change event on province:
$('#province').live('change', function() {…})
When triggered get the value from province $('#province').val() and use it to get the cities. Loop out the cities as options for the city selector (same technique as you showed above).
Whether the cities select is shown and empty or completely hidden by default is up to you.
(Depending on the number of provinces [amount of data] you could also create all selects in html and simply toggle their display)
Hope this helps!
Copy and go ;)
It fills the province-field like you do... additional there is a map created (province -> citys). The province select field gets an onChange listener. If available, the listener fetchs the cities out of the map and set them into the city-select box.
$(function() {
var data = [
{"province":"Eastern Cape","cities":"Mthatha,Njoli,Port Alfred,Port Elizabeth,Queenstown,Uitenhage"},
{"province":"Freestate","cities":"Thaba Nchu,Virginia,Welkom"}
]
var map = {};
$('#cities').attr('disabled', 'disabled');
$(data).each(function(i, data) {
map[data.province] = data.cities.split(',');
$('#provinces').append('<option value="' + data.province + '">'+data.province+"</option>");
});
$('#provinces').change(function() {
var disable = function() {
$('#cities')
.html('<option>select city</option>')
.attr('disabled', 'disabled');
}
var enable = function() {
$('#cities')
.removeAttr('disabled', 'false')
.html('');
}
if (!$(this).val()) {
disable();
return;
}
else if (typeof map[$(this).val()] == 'undefined') {
alert('invalid city');
disable();
return;
}
enable();
$(map[$(this).val()]).each(function(i, city) {
$('#cities').append(
$('<option></option>')
.text(city)
.val(city)
);
});
});
});

Categories