AJAX textfield automplete, when selected, how to change value of a combobox? - ajax

I don't really know AJAX, I'm only using a bit of its feature in my project. I used its autocomplete feature in a textfield, which connects to a mysql database. Now I want it so that when a person is selected, his/her corresponding rank (which should also be acquired the database) will automatically be the value of the combobox (something like this)...

This tutorial applies a value after select to a text field and the combobox.
http://www.jensbits.com/2010/03/29/jquery-ui-autocomplete-widget-with-php-and-mysql/
Be sure to check the demo:
http://www.jensbits.com/demos/autocomplete/
$(function() {
$('#abbrev').val("");
$("#state").autocomplete({
source: "states.php",
minLength: 2,
select: function(event, ui) {
$('#state_id').val(ui.item.id);
$('#abbrev').val(ui.item.abbrev);
}
});
$("#state_abbrev").autocomplete({
source: "states_abbrev.php",
minLength: 2
});
});

Related

How to avoid multiple radio buttons selection when paginating a data table

I'm having a problem here:
When I select a radion button in a page 1 and another one in the same page it works fine, but when I select a radio button in the page number 2, and go back to the page number 1, that first radio button still selected and the one in the page number 2 is also selected, how can I solve this problem? I was looking for a solution here in the forum but couldn't find someone with the same problem.
*[code] $(document).ready(function () { var oTable = $('#example').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers" }); }); [/code]*
There is no solution from DataTables itself. You'll have to do it on your own.
What you can do is save the selected value yourself on a click. Imagine you have a table called projectsTable. Then you can write:
var selection = -1;
$("#projectsTable input[type=radio]").on
(
"click",
function()
{
selection = $(this).val();
}
);
Then, you'll have to unselect all the wrong values every time the page changes. Add a callback in the construction of your table for page draw to do that:
//other settings go here, like the dom one
//you can choose your own, no need for this specific one
"dom": "lfBrtip",
"fnDrawCallback":
function(oSettings)
{
$("#projectsTable input[type=radio][value!="+selection+"]").prop('checked', false);
}
Every time the page is changed, this piece of code deselects everything you don't want to be selected any longer.

Kendo UI - Drop down list Setting Value autoBind = false setting

I am evaluating kendo ui right now to use in our big application. We have a situation where we have much values in dropdowns (like 200+) and there are more than 1 drop down with that size. So if we have a complex form. The Page Load takes time to render the form. (Due to that each box needs to be loaded from service and filled up).
We avoided this by writing our own asp.net web control with on demand support (like autoBind property) in the drop down list in kendo ui.
Now, DropDownList from KendoUI serves the purpose with autobind = false, BUT when setting value it fetches data from remote binding first and then selects appropriate value. (this is cool and really good for small lists) but Potentially this will mean that when we load the page and set the value it will issue remote binding calls for each of the drop downs.
Now,
Can we set value/ text to appear without issuing the remote binding. We want remote binding to be done ONLY when the user clicks on the drop down itself. (not when we are filling form). This will save extra calls to system and help quickly render the form to user.
Here is JS Bin
http://jsbin.com/ayivad/3/edit
If somebody from kendo ui would like me to help out - let me know, but this idea will allow us to use kendo ui drop downs with good use.
<input type="button" id="btnSet" value="Set Value (Click without clicking on DropDown" />
<br/><br/>
<select id="products"></select>
$(document).ready(function () {
$("#products").kendoDropDownList({
dataTextField: "ProductName",
dataValueField: "ProductID",
autoBind: false,
dataSource: {
transport: {
read: {
dataType: "jsonp",
url: "http://demos.kendoui.com/service/Products",
}
}
}
});
var combobox = $("#products").data("kendoDropDownList"),
setValue = function (e) {
if (e.type != "keypress" || kendo.keys.ENTER == e.keyCode)
combobox.value(3);
};
$("#btnSet").click(setValue);
});
Thanks,
Riz
1) Set text instead of value : http://docs.kendoui.com/api/web/dropdownlist#configuration-text
Kendo:
text String(default: "")
Define the text of the widget, when the autoBind is set to false.
Example
$("#dropdownlist").kendoDropDownList({
autoBind: false,
text: "Chai"
});
dirty alternative - Try to hijack ddl "optional label" for your needs. Load your data for the page inclusive of the value you want to show at the ddl, then initialize ddl's with optional values equal to the value you want to show. Once user opens the ddl, remote data will load, once data loaded you will ovewrite/remove the optional label and happy days.
http://docs.kendoui.com/api/web/dropdownlist#configuration-optionLabel
(Consider splitting the list, 200 long drop down us far from user friendly.)
$("#dropdownlist").kendoDropDownList({
optionLabel: "My value" });
Also consider using Kendo ComboBox, afterall auto complete after 3 chars or so sounds as quite sensible solution in case of your 200 items. We use same solution to 500 + combobox.

Update mysql table with a click of dropdownlist in the view

Can someone please help me i want to update a database record by using the dropdownlistbox,
so when i select an option from the dropdown the database is updated with that value for that record, without having to click a submit button using codeigniter.
I know the best way to go about this is with AJAX
Yeah AJAX can make it work, and doing it with jQuery can make it a lot easier. You can add an event listener to your dropdown list, listening to a change in its value:
$("#the-dropdown-list").change(function() {
var value = $(this).attr("value");
$.ajax({
url: "path/to/controller/action/",
type: "POST",
data: {value: value},
success: function() {
// whatever you want to do after
}
});
});
This will detect a change in the dropdown list value, and then send it to the controller action given in url in $.ajax object. After that you can just update the database record like you would usually do. In the controller, the new value can be obtained using $_POST['value'], since we defined type to be POST and the different values to be passed to controller action are in the data.

Loading dynamic "chosen" select elements

I am using the jQuery plugin chosen (by Harvest). It is working fine on (document).ready, but I have a button that, when clicked, uses ajax to dynamically create more select objects that I want to use the "chosen" feature. However, only the original select elements have the "chosen" features, and the new (dynamically created) do not work. I am using jQuery.get to append the new elements. Here is a sample of the code:
jQuery(".select").chosen();//this one loads correctly
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
//response contains html with 2 more select elements with 'select' class
jQuery('#stages').append(response);
jQuery(".select").chosen();//this one doesn't seem to do anything :-(
});
});
I was thinking that I need a .live() function somewhere, but I haven't been able to figure that out yet. Any help is much appreciated!
Note - I am not trying to dynamically load new options, as specified in the documentation using trigger("liszt:updated");
Ensure that the response elements have the select class.
console.log( response ); // to verify
May also be a good idea to only apply the plugin to the new element(s).
jQuery(".select").chosen();
jQuery("#add-stage").click(function() {
jQuery.get('/myurl',{},function(response) {
console.log( response ); // verify the response
var $response = $(response); // create the elements
$response.filter('.select').chosen(); // apply to top level elems
$response.find('.select').chosen(); // apply to nested elems
$response.appendTo('#stages');
});
});
Also, if /myurl is returning an entire HTML document, you may get unpredictable results.
after you code (fill the select) .write this
$(".select").trigger("chosen:updated");
I had a similar problem with Chosen. I was trying to dynamically add a new select after the user clicks on a link. I cloned the previous select and then added the clone, but Chosen options would not work. The solution was to strip the Chosen class and added elements, put the clone in the DOM and then run chosen again:
clonedSelect.find('select').removeClass('chzndone').css({'display':'block'}).removeAttr('id').next('div').remove();
mySelect.after(clonedSelect);
clonedSelect.find('select').chosen();
one way you can use chosen with ajax:
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
cache: false,
data: search
}).done(function(data){
$.each(data, function(){
$('<option />', {value: this.value, text: this.text}).appendTo(selectObj);
});
chosenObj.trigger('liszt:updated');
});
where selectObj is particular select object
But ...
Chosen is implemented very bad.
It has several visual bugs, like: select some option, then start searching new one, then remove selected and the keep typing - you will get 'Select some options' extended like 'Select some options search value'.
It doesn't support JQuery chaining.
If you will try to implement AJAX you will notice, that when you loose focus of chosen, entered text disappears, now when you will click again it will show some values.
You could try to remove those values, but it will be a hard time, because you cannot use 'blur' event, because it fires as well when selecting some values.
I suggest not using chosen at all, especially with AJAX.
1.- Download Livequery plugin and call it from your page.
2.- Release the Kraken: $(".select").livequery(function() { $(this).chosen({}); });
This is an example of Chosen dynamically loading new options form database using ajax every time Chosen is clicked.
$('.my_chonsen_active').chosen({
search_contains:true
});
$('.my_chonsen_active').on('chosen:showing_dropdown', function(evt, params){
id_tosend=$(this).attr("id").toString();
$.get("ajax/correspondance/file.php",function(data){
$('#'+id_tosend).empty();
$('#'+id_tosend).append(data);
$('#'+id_tosend).trigger("chosen:updated");
});
});

while the select editoption posts the value (or id) of the selected list item, autocomplete posts the label - i need id posted

While both autocomplete and select in jqgrid editform place the selected label into the cell, select will place the value (id) in the postdata array where autocomplete will place the label into the postdata array.
is there a way to get the editoption's autocomplete to post the item value (id) instead of the label?
here is the jqgrid code segment i'm using autocomplete in...
$('#tab3-grid').jqGrid({
colNames:['Workorder', 'wo.CUID',.....],
colModel:[
.
.
.
{name:'wo.CUID', index:'cu.LastName', width:120, fixed:true, align:'center', sortable:true, editable:true, edittype:'text',
editoptions:{dataInit:function(el){$(el).autocomplete({ source: 'php/customer-ac-script.php'
, minLength: 1
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true}, // general parameters that apply to all navigation options below.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13]}, // edit options.
{jqModal:true, navkeys:[true,38,40], savekey:[true,13], reloadAfterSubmit:false, afterSubmit: addRecordID}, // add options.
{jqModal:true, afterSubmit: serverMessage}, // del options.
{jqModal:true}, // search options.
{jqModal:true, navkeys:[true,38,40]} // view options.
);
The php code segment:
// construct autocomplete select.
$i = 0;
while($row = mysql_fetch_assoc($result)) {
$output[$i][$crudConfig['id']] = $row['CUID'];
$output[$i][$crudConfig['value']] = $row['LastName'];
logMsg(__LINE__,'I','cu.CUID: '.$row['CUID'].', cu.LastName: '.$row['LastName']);
$i++;
}
// encode to json format and send output back to jqGrid table.
echo json_encode($output);
logMsg(__LINE__,'I','Send json output back to jqGrid table: '.json_encode($output));
Would it be as simple as calling a function under the autocomplete select event or the grid before or after editform submit?
Also, i noticed this note in the jqgrid doc's for datainit: that says...
Note: Some plugins require the position of the element in the DOM and
since this event is raised before inserting the element into the DOM
you can use a setTimeout function to accomplish the desired action.
Would the lack of including the settimeout function be causing the problem?
The server code which provide the JSON response on the autocomplete request has id and value properties. On the other side the standard behavior of jQuery UI Autocomplete is to use label and value properties (see "Datamodel" in the documentation). The value of label property (if any exist) will be used to display in the contextmenu. The value of value property will be placed in the <input> field after the user choose the item from the contextmenu. The value of label property can has HTML markup, but the value of value property must be the text.
So I see the problem as pure problem of the usage of jQuery UI Autocomplete independent on jqGrid. If I understand correct your question you can solve your problem by modification your server side code.
Oleg's answer clarifying the data model for jquery UI's autocomplete, has allowed me to move forward and understand that autocomplete has nothing to do with constructing and sending the postdata array to the server, jqgrid's editform handles it. With that knowledge, i was able to answer my original question and successfully integrate autocomplete into jqgrid. So, in the interest of sharing, i'd like to show you all my motivation and solution.
By default, selecting a label from the autocomplete list put's the value of the selected label/value pair into the text box. All the editform cares about when you submit is what's in the edit fields. So when you submit the editform, the cell's postdata element value will again contain the value of the autocomplete text box. But what if while wanting to post the value of the label/value pair, you want the label of the label/value pair displayed in the text box? You have a problem! How do you get the value of the label/value pair posted to the server?
Well, after spending a few days on it, it turns out to be quite simply. While i'm sure there is more than one solution, here is mine:
add a hidden id column in the grid
define the select: and focus: events in the autocomplete function
in the select: function; insert the selected label into the text box (optional), disable the default behavior of autocomplete, then set the cell of the hidden column to the value of the selected label/value pair
in the focus: function; insert the selected label into the text box(optional), disable the default behavior of autocomplete
add an "onclickSubmit:" event to the navgrid edit options with function name something like "fixpostdata"
in the "fixpostdata" function; get the cell value of the hidden column and insert it into the postdata element associated with the cell.
The following are the grid and javascript code segments i used…
grid segments
{name:'wo_CUID', index:'wo_CUID', width: 70, hidden: true},
{name:'wo.CUID', index:'cu.LastName', width:120, sortable:true, editable:true, edittype:'text',
editoptions:{
dataInit:function(el){ // el contains the id of the edit form input text box.
$(el).autocomplete({
source: 'php/customer-ac-script.php',
minLength: 1,
select: function(event, ui){event.preventDefault();
$(el).val(ui.item.label);
var rowid = $('#tab3-grid').getGridParam('selrow');
// set the hidden wo_CUID cell with selected value of the selected label.
$('#tab3-grid').jqGrid('setCell', rowid,'wo_CUID',ui.item.value);},
focus: function(event, ui) {event.preventDefault();
$(el).val(ui.item.label);}
})
}
},
formoptions:{rowpos: 1, label:'Customer', elmprefix:'* '},
editrules:{required:true}
},
.
.
$('#tab3-grid').jqGrid('navGrid', '#tab3-pager',
{view:true, closeOnEscape:true, cloneToTop:true},
{jqModal:true, navkeys:[false,38,40], onclickSubmit: fixpostdata}, // edit options.
.
.
javascript function
// define handler function for 'onclickSubmit' event.
var fixpostdata = function(params, postdata){
var rowid = $('#tab3-grid').getGridParam('selrow');
var value = $('#tab3-grid').jqGrid('getCell', rowid,'wo_CUID');
postdata['wo.CUID'] = value;
return;
}
The fixpostdata function fires when you submit the editform but befor the postdata array is sent to the server. At this point you replace the cell's postdata element value with whatever you want. In this case, the value of the label/value pair stored in the hidden column cell. When the function returns, the modified postdata array is sent to the server.
Done!

Resources