Jquery ui - Autocomplete - Change Label of Field while keeping the same post value - jquery-ui

im working on this jquery data entry form in which i need a specific field to be autocompleted with data from mysql
i got everything working, autocomplete retrieves data from the sql through php matching is great in english/latin and utf8 characters
the values get retrieved from the sql as "'number' => 'name'"
right now the autocomplete has 3 values in the output, value, label and id.
as id and value it uses the 'name'
and the label is the 'number' of my sql string (which is posted to the next page when the form is submited)
so everyting works ok, my 'number' is posted correctly, there is a minor annoyance tho
when i select something from the autocomplete list, the field is populated with the 'number'
is there any way to fill it with the 'name'?
ie: search for 'name', get dropdown with 'names', click and get the 'name' in the field, and when i submit i get the 'number' posted?
any help would be greatly appreciated.
if you need to take a look at my code, it's posted on a previous question: Jquery ui - Autocomplete - UTF8 charset
thanx in advance :)

The usual way to do this is:
Use a hidden input to hold the value you'd like to POST, then autocomplete a separate field.
Populate the hidden input on select
Populate the visible, autocompleted input with the label property of the item that was selected.
So, for example:
HTML:
<input type="hidden" name="name" />
<input type="text" id="name_auto" />
JavaScript:
$(function () {
var cache = {},
lastXhr;
$( ".name" ).autocomplete({
minLength: 1,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
},
select: function (event, ui) {
event.preventDefault();
this.value = ui.item.label;
},
change: function (event, ui) {
if (ui.item) {
$("input[name='name']").val(ui.item.value);
} else {
$("input[name='name']").val('');
}
}
});
});

You can use the result (handler) from u'r autocomplete
where the variable data such as arrays and you can return two data at once
Expl:
in javascript
$().ready(function()
{
var url = "<?=base_url()?>index.php/master/agen";
var width_val = 308;
$("#name_auto").autocomplete(url,
{
width: width_val,
selectFirst: false,
});
$("name_auto").result(function(event, data, format)
{
$("#name_auto").val(data[0]);
$("#id").val(data[1]);
});
});
in HTML :
<input type="hidden" name="number" id="id" />
<input type="text" id="name_auto" name="name" />
in PHP :
foreach ($source->result() as $row)
{
echo "$row->nama|$row->id\n";
}
note : here I use PHP CodeIgniter in its

Related

jQuery Autocomplete wrong item in text box on select

When a user begins typing in the DRMCompanyName input text box, and autocomplete feature fires that displays both the company name and the company id. When the use clicks on a selection, the company name and id are to be placed into the DRMCompanyName text box and the id in the DRMCompanyId text box just below.
When the json results are returned from the controller, the code in the autocomplete ajax success function populates the drop down list by setting the label to be equal to the value (company name) plus the key (company id) being returned. Likewise the value is set to just the key (company id).
When the user selects a particular item, the label is supposed to go in the DRMCompanyName text box and the value in the DRMCompanyId. However, what winds up happening is the value gets placed in both.
I've scoured my code over and over and cannot find out why the label does not get placed in the DRMCompanyName field.
jQuery
$(function () {
$('#DRMCompanyName').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui);
$('#DRMCompanyName').val(ui.item.label);
$('#DRMCompanyName').text(ui.item.label);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
});
});
Here is a sample screen shot of the ui item from the select function above (the company name is blacked out for privacy). When I click on this particular item in the autocomplete drop down, 200014 gets placed in both the DRMCompanyName and DRMCompanyId fields.
Razor Markup
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyName)
#Html.ValidationMessageFor(model => model.DRMCompanyName)
</div>
<div class="M-editor-label">
#Html.LabelFor(model => model.DRMCompanyId)
</div>
<div class="M-editor-field">
#Html.TextBoxFor(model => model.DRMCompanyId, new { maxlength = 10, title = "Start typing company name to activate DRM Company Name lookup. When DRM Company is found, select to fill in DRM Company ID and DRM Company Name fields." })
#Html.ValidationMessageFor(model => model.DRMCompanyId)
</div>
EDIT
After following the suggestion in the answer below, I modified the select function like so:
select: function (event, ui) {
console.log(tempResults[ui.item.value]);
$('#DRMCompanyName').val(tempResults[ui.item.value]);
$('#DRMCompanyName').text(tempResults[ui.item.value]);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(ui.item.value);
$('#DRMCompanyId').text(ui.item.value);
}
}
Based on the console.log readout, this accesses the correct value when the user clicks on the autocomplete item. However, it still places the value in both text boxes. What I can't understand, when I select Inspect Element, is that the correct value for DRMCompanyName actually is placed in the HTML, however it does not appear on the screen, only the id or value (as opposed to label).
You are setting label: value + " " + key which will of course add the id in the label.
When you set $('#DRMCompanyName').val(ui.item.label);, it's going to set what you concatenated in the $.map to the value.
One way to do this is to store a temporary result set from the data in the source ajax call to access later. With this temp set, you can now pull any object or key/value from it for use later.
When getting results, store a temporary list of the results.
var tempResults = [];
...
source: function (request, response) {
$.ajax({
url: '#Url.Action("compSearchByName", "AgentTransmission")',
type: 'GET',
dataType: 'json',
data: request,
success: function (data) {
tempResults = data;
response($.map(data, function (value, key) {
return {
label: value + " " + key,
value: key
};
}));
},
});
}
Then, on the select, you can now access the stored data and set values:
select: function (event, ui) {
event.preventDefault();
var name = tempResults[ui.item.value].value;
var id = tempResults[ui.item.value].key;
$('#DRMCompanyName').val(name);
$('#DRMCompanyName').text(name);
if ($('#DRMCompanyId').text() == '') {
$('#DRMCompanyId').val(id);
$('#DRMCompanyId').text(id);
}
}
EDIT
Forgetting one minor thing! Add this to the beginning of the select: function!
event.preventDefault();
By default, when selecting, the autocomplete will use the ui.item.value to populate the element that it's wired up with. Using event.preventDefault() will prevent the already wired up event handler to be called used within the autocomplete.
event.preventDefault() documentation.

jquery Select2 Ajax - How set value (initSelection)

How set in the drop-down list item selected by the user?
Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?
I have working script which retrieve data for the list.
$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
url: "index.php?modul=getusers",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return { results: data };
}
},
allowClear: true,
formatSelection: function(data) {
return data.text;
}
});
Standard data in ajax call:
{"text":"sample text", "id":"1"}
Input:
<input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid">
I tried to add the following code, but it doesn't work
initSelection: function(element, callback) {
var id=$(element).val();
if (id!=="") {
$.ajax("index.php?modul=getusersfriend&q="+id, {
dataType: "json"
}).done(function(data) { callback(data); });
}
},
Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.
But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.
You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.
Which is what would happen here:
var id=$(element).val();
Here is a simple example of serializing your form.
PS: Don't really see what bootstrap has to do with anything.

Connect knockout and jQueryUI autocomplete

I have a jQueryUI autocomplete that pulls from a list of customers and is attached based on the selector [input data-role="customer-search"]. Once a customer is selected, I make a AJAX call to get the full customer detail. This part I have working fine. The issue is that I am having trouble figuring out a way to incorporate knockout into this. My ideal situation is a custom binding like "onSelect: customerSelected", which would take in the selected Customer JSON and integrate it into the overall model, which would then cause updates to a bunch of fields on the page with bingings such as model.Customer.Address, model.Customer.Type.
The place I am butting my head against is that connection point after I've gotten the Customer JSON back from the AJAX call, how to send it to the "customerSelected" method on the viewmodel tied to the same input I attached the jQuery autocomplete.
Here is a simplified version of a bindinghandler my team wrote for handling autocomplete. When an item is selected, the item is inserted into an observable array in the view model. It is bound in the following manner:
<input type="text" data-bind="autoComplete:myObservableArray, source:'myUrl'" />
You can customize what happens when an item is selected in the 'select:' area.
ko.bindingHandlers.autoComplete = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var postUrl = allBindingsAccessor().source; // url to post to is read here
var selectedObservableArrayInViewModel = valueAccessor();
$(element).autocomplete({
minLength: 2,
autoFocus: true,
source: function (request, response) {
$.ajax({
url: postUrl,
data: { term: request.term },
dataType: "json",
type: "POST",
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
var selectedItem = ui.item;
if (!_.any(selectedObservableArrayInViewModel(), function (item) { return item.id == selectedItem.id; })) { //ensure items with the same id cannot be added twice.
selectedObservableArrayInViewModel.push(selectedItem);
}
}
});
}
};
Hopefully, it's something like this that you're looking for. If you need something clarified, let me know.
Note Besides jquery and knockout, this example uses underscore.js ( the _.any() function)
valueUpdate: blur
data-bind="value: textbox, valueUpdate: blur" binding fixed the problem for me:
$(function() {
$(".autocomplete").autocomplete({
source: [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Scheme"]
});
});
var viewModel = {
textbox: ko.observable()
};
ko.applyBindings(viewModel);
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<input type="text" class="autocomplete" data-bind="value: textbox, valueUpdate: blur"/>

Multiple Autocomplete box using same Ajax

I want to have two different Autocomplete boxes but both using the same AJAX method in the background.
Here is my script
$(document).ready(function () {
$("#SearchProject")
.each(function () {
var urlloc = "/Project/FindProjects";
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: urlloc, type: "POST", dataType: "json",
data: { searchString: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.name, value: item.name, id: item.id }
}))
}
})
},
select: function (event, ui) {
$("[id$='ProjectID']").val(ui.item.id);
// alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
// : "Nothing selected, input was " + this.value);
}
});
});
});
I want my input fields on the form as below.
<input id="SearchProject" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID" value="" />
<input id="SearchProject2" name="SearchProject" type="text" value="" /><input type="hidden" name="ProjectID" id="ProjectID2" value="" />
When autocomplete select is complete I want the corresponding hidden field to be updated.
How do i achieve this?
Two possibilities:
First (the one I prefer): extract your auto-complete setup into a method:
function configureAutocomplete(autoField, updatedField)
You call this method for as many auto-complete fields as you want, passing it two JQuery selectors: the selector for the auto-complete field, and the hidden update field.
The other way is to base the ID of the hidden field on that of the auto-complete field. This will let you use an each to attach behavior to the fields, but I think it' more trouble than it's worth.

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});

Resources