Clear selected option in Select2 - javascript

I have new problem with my Select2 option. I can't clear my select box.
As in JSFiddle I do 'select' for my data. The problem lies in the fact that I can not remove the last element, or clear the whole field in my web portal, but in JSFiddle everything looks ok. My portal gives me error "Type Error: a is null" and I don't know why. Here is my code:
$.getJSON(url, function (data){
$("#mySelect").select2({
data:data,
placeholder: "Select options",
templateSelection: function(val) {
return val.text;
}
});
});
And my select:
<select id="mySelect"></select>
The problem disappears when I use other solution but then I can not invoke the relevant data for 'templateSelection'. In this solution I create options for my select, and simple use select2 but as You can see for the field 'data.version' I have the answer "undefined"
Code:
var data=[
{id:1, text: "sample_1", version: "1"},
{id:2, text: "sample_2", version: "2"}];
$.each(data, function(i,x){
$('#mySelect').append($('<option>', {
value: x.id,
text: x.text
}));
});
$("#mySelect").select2({
templateResult: function(data) {
return data.text + ' ' + data.version;
}
});
JSFIDDLE
Any sugestion why this solution work in jsfiddle, but not in my portal?

var data=[{id:1, text: "sample_1", version: "1"},{id:2, text: "sample_2", version: "2"}]
$.each(data, function(i,x){
$('#mySelect').append($('<option>', {
value: x.id,
text: x.text+" "+x.version,
}));
});
$("#mySelect").select2({
templateResult: function(data) {
return data.text;
}
});
when $ function is used to create element it can only accept html attributes of that element

Related

UI-Select2 binding to object instead of property of object

I am using ui-select2, version 3.5.2, trying to do a single select, type-ahead and retrieve from REST api, drop down list.
It looks like it is working except for one major issue, which is that, the ng-model's property gets set to an object {Id: "some id", text: "some text"} instead of the actual Id property. I cannot figure out how to tell ui-select2 control to set the ng-model property to the "Id" field of the object, instead of the whole object.
I have tried various hacks with watchers but didnt get anywhere. I am sure there is something that I am missing because this is something that should be possible easily.
Here is my javascript code:
$scope.selectOptions = {
placeholder: '- Select Value -',
allowClear: true,
minimumInputLength: 2,
initSelection: function (element, callback)
{
if ($scope.myobj && $scope.myobj.Id && $scope.myobj.Id !== '00000000-0000-0000-0000-000000000000')
{
$.ajax("../../api/objs/" + $scope.myobj.Id).done(function (data) {
var res = $(data).map(function (i, o) {
return {
id: o.Value,
text: o.Display
};
}).get();
callback(res[0]);
});
}
},
ajax:
{
type: "GET",
url: function (term) {
return ["../../api", "objs", encodeURIComponent(term)].join("/");
},
dataType: "json",
contentType: "application/json",
cache: false,
results: function (data, page) {
return {
results: $(data).map(function (i, o) {
angular.extend(o, {
id: o.Value,
text: o.Display
});
return o;
}).get()
};
}
}
}
Here is my html code:
<div ui-select2='selectOptions' ng-model="myobj.Id" style="width:215px" />
I got around this by binding to a separate property and then adding a ng-change on my div and syncing the binding property's id field to actual property on my object.

jquery autocomplete - selected value disappears from textbox

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);
}
});

Enabling jQuery Autocomplete on dynamically created input fields

I've read almost every article i could find on how to accomplish this, but i'm still failing miserably. mostly because i'm an amateur at jQuery/Javascript.
I have a website that contains one input element. I've managed to get jQuery Autocomplete working nicely on this. The problem is that when i dynamically add additional elements using the .append method, these new elements do not work with autocomplete.
See jsfiddle: http://jsfiddle.net/aktive/r08m8vvy/
see jsfiddle for full code sample
Thankyou in advance for your help!! :)
-Dean
You must bind autocomplete after adding new elements
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
});
See example: http://jsfiddle.net/r08m8vvy/4/
I actually found that a more reliable way was to bind using 'on' with the 'focus' action to init the auto complete based on the field class and destory it on exit. This way it cleans up the garbage and only inits it once you need to.
I was using it with cloning rows though and even doing deep cloning, which would clone the plus and minus buttons for the rows, it wasn't cloning the autocomplete.
var auto_opts = {...opts...}
$('body').on('focus', '.search_field', function(){
$(this).autocomplete(auto_opts).on('blur', function(){$(this).autocomplete('destroy')});
});
It also means that you aren't forced into using the last row because it works on the field as you focus on it
See http://jsfiddle.net/r08m8vvy/2/
Give the new input an ID and call autocomplete on it. The initial autocompate call you make won't include the dynamically added inputs.
$(wrapper).append('<div><input id="' + x + '" type="text" name="mytext"/>Remove</div>'); //add input box
$( "input[id="+ x +"]" ).autocomplete({
source: availableAttributes
});
I Updated the fiddle http://jsfiddle.net/r08m8vvy/5/
You have to bind the autocomplete for new element
$(wrapper).append($('<div><input type="text" name="mytext[]"/>Remove</div>').find(":text").autocomplete({
source: availableAttributes
}));
Here is the simpler way to use autocomplete for dynamically created input fields.
$('body').on('focus', '.dynamic-input-class', function (e) {
$(this).autocomplete({
minLength: 2,
delay: 500,
source: function (request, response) {
$.ajax( {
url: "server side path that returns json data",
data: { searchText: request.term},
type: "POST",
dataType: "json",
success: function( data ) {
$("#data-success").html(data.returnedData); //returnedData is json data return from server side response
}
});
}
});
});
<script>
$(document).ready(function() {
var nhlTeams = ['Atlanta', 'Boston', 'Buffalo', 'Calgary', 'Carolina', 'Chicago', 'Colorado', 'Columbus', 'Dallas', 'Detroit', 'Edmonton', 'Florida', 'Los Angeles', 'Minnesota', 'Montreal', 'Nashville', ];
var nbaTeams = ['New Jersey', 'New Rork', 'New York', 'Ottawa', 'Philadelphia', 'Phoenix', 'Pittsburgh', 'Saint Louis', 'San Jose', 'Tampa Bay', 'Toronto Maple', 'Vancouver', 'Washington'];
var nhl = $.map(nhlTeams, function (team) { return { value: team, data: { category: 'Section A' }}; });
var nba = $.map(nbaTeams, function (team) { return { value: team, data: { category: 'Section B' } }; });
var teams = nhl.concat(nba);
// Initialize autocomplete with local lookup:
$('body').on('focus', '.db_items', function(){
$(this).autocomplete({
lookup: teams,
minChars: 1,
onSelect: function (suggestion) {
$('#selection').html('You selected: ' + suggestion.value);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
groupBy: 'category'
});
});
});
</script>

Select2 inserts an empty text option in the dynamic list

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);
}

Get user input from single select box using Select2

Issue
I just started using Select2 (http://ivaynberg.github.io/select2/) and I am trying to do a basic task.
I have a select box that has, for example, 3 items in it. I want to be able to have the user either select 1 of the 3 results or type in their own result and then eventually, on submit, it will submit whatever value is in the box.
What I've Tried
<input style="width: 200px;" type="hidden" id="foo" />
<script type="text/javascript">
$(document).ready(function () {
$("#foo").select2({
query: function (query) {
var data = { results: [{ text: 'math' }, { text: 'science' }, { text: 'english' }] };
data.results.push({ text: query.term });
query.callback(data);
}
});
});
</script>
The code above allows me to see the 3 results and type in a result myself. But I am unable to get the typed in result to "stick" when I click away, hit enter, or select the result I just typed in. Same goes for the select options, but I am most concerned with the user inputted text.
Here's what it looks like:
The parameter createSearchChoice allows you to do just what you want. Here is an example:
<script type="text/javascript">
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term)===0; }).length===0) {
return {id:term, text:term};
}
},
multiple: false,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
</script>
Taken from a closed issue at: https://github.com/ivaynberg/select2/issues/201
Fiddle: http://jsfiddle.net/pHSdP/2/
Also, make sure you add a name to the input, otherwise you won't see the value at server side
<input style="width: 200px;" type="hidden" id="foo" name="foo" />
Just a quick note for anyone else who's having a different data input. In case the console says " this.text is undefined ", make sure you check your text tag, like this:
<script type="text/javascript">
// Data input taken from "label", not "text" like usual
var lstData = [{id: 0, 'label': 'story'},{id: 1, 'label': 'bug'},{id: 2, 'label': 'task'}];
$("#foo").select2({
createSearchChoice:function(term, data) {
if ($(data).filter(function() {
return this.label.localeCompare(term)===0; }).length===0) {
return {id:term, 'label':term};
}
},
data: { results: lstData, text: 'label' }
});
</script>
Library you are using is used to filter options in a select box. It doesn't take new input, as per their own documentation:
Select2 is a jQuery based replacement for select boxes.It supports searching, remote data sets, and infinite scrolling of results.
I would suggest you to use jQueryUI Autocomplete or TypeAhead

Categories

Resources