I have this autocomplete in a input box and all is working fine:
$(function() {
$("#customer").autocomplete({
minLength: 1,
source: function(request, response) {
$.getJSON('url.php', { 'string': request.term }, function(data) {
if(data) {
var clienti = data.error ? [] : $.map(data, function(customer) {
return {
label: customer.fullname,
array: customer
};
});
response(clienti);
}
});
},
select: function( event, ui ) {
$("#description").val(ui.item.array.description);
}
})
});
I want to call (trigger) the same autocomplete function ON LOADING another page, but WITHOUT select an item! (simply by pass data to Ajax).
If i use $("#customer").autocomplete("search") all is working BUT i need to select the ITEM to view the $("#description").val !
$("#customer").val is loaded by PHP on page load.
How could i do?
Thank you.
Related
I'm programming in ASP.NET MVC5. On one of my views I need to be able to create a search bar. For this example, lets say you are searching for names. When you start typing a person's name, all of the results will be displayed in a drop down list as you type.
Here is the tricky part that I need help with. I want there to be a button for each entry in the drop down list to "Add" that person name to a table.
For example, I'm looking for the name "Debo" As I type "D-E-B", I see the name I want in the drop down list. I click "Add" and it removes the name "Debo" from the drop down list and adds it to my table. Once "Debo" has been added to the table, I need to be able to see Debo's age and gender that I wouldn't see in the drop down list.
I don't have any code examples because I'm not even sure where to start. I've researched this like crazy, but I cannot find anything. Any help or pointing me in the right direction, will be greatly appreciated,
I am using autocomplete by JQueryUI.
Please refer below code hopefully it will helps you.
JavaScript Code:
$("#member_CompanyName").autocomplete({
highlightClass: "bold-text",
search: function () {
$(this).addClass('working');
},
source: function (request, response) {
var companyDetails = new Array();
$.ajax({
url: "/ControllerName/JsonActionResult",
async: false,
data: {
"parm": request.term
},
success: function (data) {
if (data.length === 0) {
companyDetails[0] = {
label: "No Result Found",
Id: ""
};
} else {
for (var i = 0; i < data.length; i++) {
companyDetails[i] = {
label: data[i].Value,
Id: data[i].Key
};
$("#no-companyfound").css("display", "none");
}
}
}
});
response(companyDetails);
},
minLength: 2,
select: function (event, ui) {
/*Select Function works on when you selects element from Response List*/
$.ajax({
async: false,
url: "/ControllerName/JsonActionResultonClick",
data: {
"id": ui.item.Id
},
success: function (data) {
// Do your success logic here
},
error: function (xhr, ajaxOptions, thrownError) {
// Error Logic here
}
});
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Controller Code:
[HttpGet]
public JsonResult JsonActionResult(string parm) {
// Replace your special Character like "-,~" etc from your search string
var result = new List < KeyValuePair < string,
string >> ();
foreach(var item in _obj_fulldetails.GetCompanylistSearch(parm)) {
result.Add(new KeyValuePair < string, string > (item.Value.ToString(), item.Text));
}
return Json(result, JsonRequestBehavior.AllowGet);
}
You can implement "Add"
button your logic on Item select. If you still want add button you can edit response string into JS.
See my response screenshot :
I have written a custom jquery autocomplete function to display certain values and textfields to update on selecting the value as per the code below:
<input type="text" name="promoitem" id="promoitem">
$('#promoitem').autocomplete({
source: "BckProcesses/GetPromoItems.asp",
create: function() {
$(this).data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.append('<a>' + item.promodesc + '</a>')
.appendTo(ul);
}
},
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
}
});
This is what is return by the source file (GetPromoItems.asp)
[{"id": "1", "promodesc": "Ipad 4 ", "promocost": "200", "qty": "1"},{"id": "2", "promodesc": "Village Tickets", "promocost": "20", "qty": "2"}]
However, when I select the value from the ul, everything gets populated except the promoitem textfield. That fields goes to being blank.
Can anyone please let me know what could be causing this?
Thanks
Sam
Since you're providing your own logic in the select handler, you need to prevent the default action, which is to place ui.item.value in the input.
Right now, your code is running, and then jQueryUI is immediately trying to place ui.item.value in the input, which explains the empty value.
So really all you need to do is call event.preventDefault(); or return false; from the select handler:
select: function(event, ui) {
$('#promoitem').val(ui.item.promodesc);
$('#promocost').val(ui.item.promocost);
$('#promoqty').val(ui.item.qty);
$('#hidden_promo_item_id').val(ui.item.id);
event.preventDefault(); // <---
}
After spending an hour, finally got to an point that Jquery UI autocomplete sets the value to default.
Only one line needs to put and prevent Jquery default function to get the wok done.
// pincode list autocomplete
$('input[name=\'pincode\']').autocomplete({
'source': function (request, response) {
$.ajax({
url: 'index.php?route=seller/pincode/pincodeAutocomplete&filter_name=' + encodeURIComponent($('input[name=\'pincode\']').val()),
dataType: 'json',
success: function (json) {
json.unshift({
pincode_id: '',
pincode: '-- None --'
});
response($.map(json, function (item) {
return {
label: item['pincode'],
value: item['pincode_id']
}
}));
}
});
},
'select': function (event, ui) {
event.preventDefault();
$('input[name=\'pincode\']').val(ui.item.label);
$('input[name=\'pincode_id\']').val(ui.item.value);
}
});
I am using Select2 with Jquery-editable and encountering an abnormal behavior of Select2, what I am doing is displaying editable table of information using ejs template, and as user clicks on CBA opens up a select2 box which have the originally selected result, and then user can add or delete options in it, options comes from Database source, and when user selects an options it adds an empty option in database with the selected option , the array looks like this
[ "ABCD", "ONAB", "" , "BCNU" ]
I read somewhere about allowClear: true and add a placeHolder but It doesn't helped me at all. As everything is done dynamically I can't find where that empty option is added.
Code is below:
Ejs/HTML code for Select 2
<tr>
<td width="40%">Select CBA(s)</td>
<td>
<a class="cbaSelectUnit" data-emptytext="Select CBA(s)" data-original-title="Select CBA(s)" data-type="select2"></a>
</td>
Javascript for Select 2
$("a[data-name='Cba']").editable({
showbuttons: 'false',
emptytext: 'None',
display: function(values) {
var html = [];
html.push(values);
$(this).html(html);
},
select2: {
multiple: true,
allowClear: true,
placeholder: "Select CBA(s)",
ajax: {
// url is copied from data-source via x-editable option-passing mechanism
dataType: 'json',
// pass the '?format=select2' parameter to API call for the select2-specific format
data: function(term, page) {
return {
deptId: departmentId,
format: 'select2'
};
},
// transform returned results into the format used by select2
results: function(data, page) {
return {
results: data
};
}
},
// what is shown in the list
formatResult: function(cba) {
return cba.text;
},
// what will appear in the selected tag box
formatSelection: function(cba) {
return cba.text;
},
// rendering id of the values to data.value requirement for Select 2
id: function(cba) {
return cba.value;
},
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
id: v,
text: v
};
});
callback(result);
}
}
});
Format in which Code is returned from the database:-
Facility.findOne({ _id: department.Facility }, function(err, facility) {
if (err) {
res.send(500, err);
} else if (!facility) {
res.send(404, 'Facility not found');
} else if (req.query.format && req.query.format === 'select2') {
var result = facility.Cba.map(function(c) {
return { value: c, text: c };
});
res.json(result);
}
});
Image showing an empty box added by itself
How Array looks after I edit
So it was just a simple syntax error, I was doing found out by myself,
I was returning cba.value as id, but the initSelection was returning
{id: v, text: v}
it should be value & text instead of id & text.
// what is shown in the selected-tags box
initSelection: function(element, callback) {
var id = $(element).val(),
result = id.replace(/^,\s*$/, ',').split(",").map(function(v) {
return {
value: v,
text: v
};
});
callback(result);
}
How can I avoiding duplicates tags in Select2 input?
When I type tag name on the keyboard string is added to input field, but when I select tag from dropdown list (results from the database) the id is added to input (look at console.log on screenshot). So I can select tag from list and add the same tag from keyboard.
Moreover, I need the text of tags, not id from dropdown list while submit a form.
Full resolution
HTML:
<input type="hidden" id="categories" name="categories" style="width:100%" value="${categories}">
JS:
$("#categories").select2({
tags: true,
tokenSeparators: [","],
placeholder: "Dodaj",
multiple: false,
minimumInputLength: 3,
maximumInputLength: 50,
maximumSelectionSize: 20,
ajax: {
quietMillis: 150,
url: '${request.route_url("select2")}',
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page,
};
},
results: function (data, page) {
var more = (page * 10) < data.total;
return {results: data.categories, more: more};
}
},
initSelection: function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
createSearchChoice: function (term) {
return { id: term, text: term };
},
}).change(function (e) {
if (e.added) {
console.log($("#categories").val())
console.log(e)
}
});
Have same problem, but I figured it out to find a way around.
I'm getting text and ids, but on the server side I'm creating from given id new objects, which are well read.
$tagsArray = explode(',', $tagNames); // it contains of my input select2 value (with ids)
foreach ($tagsArray as $tag)
{
if (is_numeric($tag))
{
$tags->append(TagQuery::create()->filterById($tag)->findOneOrCreate());
}
elseif (!empty($tag))
{
$tags->append(TagQuery::create()->filterByName($tag)->findOneOrCreate());
}
}
Hope it helps.
at first use select 2
and then do this:
$("select").change(function() { var tr = $(this).closest("tr");
tr.find("select option").attr("disabled",""); //enable everything
//collect the values from selected;
var arr = $.map
(
tr.find("select option:selected"), function(n)
{
return n.value;
}
);
//disable elements
tr.find("select option").filter(function()
{
return $.inArray($(this).val(),arr)>-1; //if value is in the array of selected values
}).attr("disabled","disabled"); });
I am having some trouble getting autocomplete to work specifically with a json file. It
giving following error whenever something is entered in the text box
url is undefined
following is my jQuery code
$(document).ready(function() {
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function(item) {
return item.value;
}));
})
}
});
});
and the JSON
{
"ledgers":
[
{
"id":"2001",
"name":"Bharat"
},
{
"id":"2003",
"name":"Gaurav"
},
{
"id":"2002",
"name":"Pankaj"
},
{
"id":"2022",
"name":"Purchase"
},
{
"id":"2007",
"name":"Ram"
},
{
"id":"2008",
"name":"Ramesh"
},
{
"id":"2009",
"name":"Suresh"
}
]}
Your JSON file format needs to contain value or label (or both). Change name to value and it should work fine.
$('#autocomplete').autocomplete({
minChars: 1,
source: function(request, response) {
var url='dataa.json';
$.getJSON(url,{term: request.term},function(data){
response($.map(data.ledgers, function (value, key) {
return {
label: value,
value: key
};
}));
})
}
});
Try adding 'use strict'; at the top of your $(document).ready(). That may point out what the problem is...
return item.value;
item does not have a value, try returning id or name, which it does have.