I want to autocomplete a drop down list.
This is my json string:
[{"ID":1,"Name":"david"},{"ID":2,"Name":"Paul"}]
This is my input:
<input type="text" id="tbNames" />
and this is my javascript:
//datas variable contains the json string
function BindNames(datas) {
$('#tbNames').autocomplete({
source: datas,
minLength: 0,
scroll: true,
select: function (event, ui) {
$("#tbNames").val(ui.item.Name);
return false;
}
}).focus(function () {
$(this).autocomplete("search", "");
});
}
The problem is that when I click on the 'tbNames' input the drop down list is displayed but names inside are not displayed BUT there are the names inside the list because when I click on on the drop down list one of the two name is displayed inside my input.
http://jsbin.com/wudidaqapo/1/edit?html,css,js,console,output
Thanks for your help.
Try this:
function BindNames() {
var datas=[{"ID":1,"Name":"david"},{"ID":2,"Name":"Paul"}];
$('#tbNames').autocomplete({
source: function (request, response) {
response($.grep(($.map(datas, function (v, i) {
return {
label: v.Name,
value: v.ID
};
})), function (item) {
return item.label;
}));
},
minLength: 0,
scroll: true,
}).focus(function () {
$(this).autocomplete("search", "");
});
}
Please see if it help for you.please use the 'label' property in your json object which the Autocompleter uses to find matches
[{"ID":1,"Name":"david","label":"david"},{"ID":2,"Name":"Paul","label":"Paul"}]
Related
I've been trying to get the dropdown items which typeahead.js retrieves me by their class name.
What I'm trying to do is a function which writes a message into the console when the dropdown item is clicked, but it is not happening.
This is what I'm doing:
var path = "{{ route('explore.autocomplete') }}";
$('input.typeahead').typeahead({
hint: true,
minLength: 1,
displayKey: 'name',
items: 3,
dupChecker: true,
source: function (query, process) {
$.get(path, { query: query }, function (data) {
return process(data);
})
},
});
$('input').click(function() {
console.log('You clicked');
})
These are the elements which I'm trying to get:
https://imgur.com/KqPusoi
I know there are a few questions about this, but I couldn't find anyone that sets the value and also triggers the select function.
My code is:
$("#ux-selfservice-account-edit-nationality").autocomplete({
source: countryList,
minLength: 1,
autoFocus: true,
select: function(event, ui) {
$(this).val(ui.item.label).attr("oid", ui.item.oid);
var select = $(this).closest(".ux-selfservice-account-box-edit").find(".ux-selfservice-account-edit-dni-type");
// Check if the user has selected a different country (against the site)
if (ui.item.iataCode == options.countryCode) {
$(select).find("option").show();
}
else {
$(select).find("option:not([value='PAS']):not([value=''])").hide();
if ($(select).val() != "PAS") $(select).val('');
}
return false;
},
focus: function(event, ui) {
return false;
},
search: function(event, ui) {
$(this).attr("oid", "0");
}
});
The countries list is something like this:
[
{
iataCode: "AR",
label: "Argentina",
value: "Argentina",
oid: 28515
},
....
]
As you can see I have a very small check in the select function, if the user selects a different country I hide or show some options from another select drop down.
Now my problem is that sometimes I want the country to be set by javascript, so that the user sees the country name in the field, the oid is set to the attr and also checks the country.
Now I am doing something like this..
$("#ux-selfservice-account-edit-nationality").val(getCountryName(profile.personalInfo.country)).attr("oid", profile.personalInfo.country);
But of course this is wrong and doesn't check the other validation. also I can't do the validation here because I don't have the countryCode (iataCode). I know I can find it in the list, but the point is to use the same function of the autocomplete..
Why don't you extract the logic in the select event handler to a separated function that you can call elsewhere from your Javascript code?
All you need in that function is the country input (which is this in your current code, and the selected country json, which is the ui.item);
So you could extract your current logic into a new function countrySelected:
var countrySelected = function (countryInput, countryJSON) {
$(countryInput).val(countryJSON.label).attr("oid", countryJSON.oid);
var select = $(countryInput).closest(".ux-selfservice-account-box-edit").find(".ux-selfservice-account-edit-dni-type");
// Check if the user has selected a different country (against the site)
if (countryJSON.iataCode == options.countryCode) {
$(select).find("option").show();
} else {
$(select).find("option:not([value='PAS']):not([value=''])").hide();
if ($(select).val() != "PAS") $(select).val('');
}
}
Then update your autocomplete declaration so the select event handler uses this function:
$("#country").autocomplete({
minLength: 1,
source: countries,
autoFocus: true,
select: function (event, ui) {
//just call the new function
countrySelected(this, ui.item);
return false;
},
focus: function (event, ui) {
return false;
},
search: function (event, ui) {
$(this).attr("oid", "0");
}
});
This way you can also manually call the countrySelected function:
var countries = [{
iataCode: "AR",
label: "Argentina",
value: "Argentina",
oid: 28515
},
...
];
countrySelected($("#country"), countries[0]);
I have created this fiddle where you can see it in action.
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.