Setting default values with selectize api for listbox in selectize.js - selectize.js

I am trying to set default value upon page load in a dropdown listbox which loads value thru an ajax call. Not able to set values using setValue method as suggested in the docs. Please help. Following are code snippets from the project
HTML
<select name="country" placeholder="Please Select Country ..."></select>
Data population JS code
$('[name="country"]').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
preload: true,
create: false,
render: {
option: function(item, escape) {
return '<div>' + escape(item['name']) + '</div>';
}
},
load: function(query, callback) {
$.ajax({
url: '/countrydata',
type: 'GET',
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
});
Default Value Setting Code
$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue("Japan");
Is there a hack where I can circumvent the problem ? I am been trying to get this work for couple of days now.
Thank you for reading. Any help would be appreciated.

You're close, but I believe your issue is that you're attempting to set the value to an option that doesn't exist in the list. You need to add the option first:
$('[name="country"]').selectize();
var item = {};
item.name = "Japan"; //Based on your render function, which uses item['name'] and labelField, searchField, etc.
$('[name="country"]')[0].selectize.addOption(item);
$('[name="country"]')[0].selectize.setValue(item.name);

Related

Sharepoint survey: Dynamically update lookup

I currently am working on designing a Sharepoint survey.
The first question is a lookup from a list, which looks like this:
Course1
Course2
Course3
Course4
Now, the user has to select one of these answers. While I got the lookup working, I have problem in updating the list.
the idea is, that the user can add his own courses to complement the list.
So for example, he can select OTHER and type in Course5 into a textbox, which should then be added to the list. The next user should then be able to select Course5 from the drop down list.ยจ
I have problems writing the result of a survey into the list - is this even possible?
Kind regards.
In choice field, it provide the 'fill-in' feature, unfortunately, the lookup column can't provide this feature.
As a workaround, we can using jQuery append a textbox and a button in the lookup column below in the newform.aspx page. Add some text in the textbox and click the "Add" button, then add data to the lookup list. The following example for your reference:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var questionTitle="question1";
var lookupListName="CL30";
$(function(){
$("select[title='"+questionTitle+"']").closest("td").append("<input id='lookupitemTitle' type='text'/> <input id='addlookupitembtn' type='button' value='Add'>");
$("#addlookupitembtn").click(function(){
if($("#lookupitemTitle").val().trim()!=""){
AddListItem(lookupListName);
}
});
});
function AddListItem(listName){
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": { "type": itemType },
"Title": $("#lookupitemTitle").val()
};
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
var item=data.d;
$("select[title='"+questionTitle+"']").append("<option selected='selected' value='"+item.ID+"'>"+item.Title+"</option>");
},
error: function (data) {
alert("Error");
}
});
}
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>

Instafeed pagination and limit not working for chosen tag, yet same code works for other tags

The following Instafeed code shows not 5 but 6 images, and the #load-more button is hidden, indicating hasNext() is false:
var tagged_cofiwear = new Instafeed({
target: 'instagram-tagged',
get: 'tagged',
tagName: 'cofiwear',
clientId: '8852afa8788546a199c37543b77b043c',
sortBy: 'most-recent',
limit: 5,
template: '<a target="_blank" href="{{link}}"><img src="{{image}}" /></a>',
after: function() {
if (!this.hasNext()) {
$('#load-more').hide();
}
}
});
tagged_cofiwear.run();
$('#load-more').on('click', function() {
tagged_cofiwear.next();
});
To try and troubleshoot, I found a jsfiddle with Instafeed pagination that works (http://jsfiddle.net/unuLyzx0/107/) and edited tagName: 'justanotherinvegas' to be tagName: 'cofiwear'.
Here is the result, which also shows the wrong number and the load more button doesn't work :(
http://jsfiddle.net/unuLyzx0/108/
Any tips?
Thanks!
In case it helps anyone else:
Turns out I needed to add the userId and accessToken for the user cofiwear, which happens to be the tag we want from all users.

Instafeed and Masonry

I have this code below where I am trying to use Instafeed and Masonry together. Everything works fine until I click the "Load more" button. Then the Masonry layout breaks. It's probably because something is loading before the other or vice versa. I'm new to this so all help would be greatly appreciated.
I got the tip to use imagesLoaded instead of window.load and also to use appended method. But I don't understand how to incorporate that in to my code.
My code is in a script.js doc and outputs in the footer of the page after instafeed.js and masonry.
$(function () {
var loadButton = document.getElementById('load-more');
if(loadButton !== null) {
var userFeed = new Instafeed({
get: 'user',
userId: xxxxxxxxx,
accessToken: 'xxxxxxxxx',
limit: 6,
resolution: 'standard_resolution',
template: '<div class="col30 grid image-top-fill instapic"><img src="{{image}}" alt="Instagram" /> <p class="nomargin">{{caption}}</p></div>',
after: function() {
if (!this.hasNext()) {
loadButton.setAttribute('disabled', 'disabled');
Masonry.start();
}
}
});
loadButton.addEventListener('click', function() {
userFeed.next();
});
userFeed.run();
}
});
$(window).load(function(){
var container = document.querySelector('#instafeed');
var msnry = new Masonry( container, {
itemSelector : '.instapic',
isAnimated : true,
isFitWidth : false
});
});
Thanks in advance for your help! Let me know if there is anything more you need from me.
Cheers / Jeppe
You're correct in that Masonry is trying to work with elements before they're loaded. You can put .masonry('appended', $items) in the after event of Instafeed. Instafeed's developer posted this fix:
https://github.com/stevenschobert/instafeed.js/issues/118#issuecomment-44438003

Cannot pass Select2 parms into UI-select2

I'm trying to use the ui-select2 Angular directive, and the github repo states:
All the select2 options can be passed through the directive. You can read more about the supported list of options and what they do on the Select2 Documentation Page
I have the directive working, but am unable to pass in simple options (ie: they are ignored).
For example:
html
<form>
<input type='hidden' ui-select2='selectGenes' ng-model='selectedGene' , ng-required="true">
</form>
js
$scope.selectGenes = {
minimumInputLength: 2,
'ajax': {
url: "/api/genes.json",
dataType: 'json',
data: function(term, page) {
return { q: term };
},
results: function(data, page) {
var index;
for (index = 0; index < data.length; ++index){
data[index].text = data[index].name2;
};
return { results: data };
}
}
};
I worked it out. The Select2 parms need to be quoted.
$scope.selectGenes = {
'minimumInputLength': 2,
'placeholder': 'Enter Gene',

select2 plugin works fine when not inside a jquery modal dialog

I am using select2 plugin inside a jquery dialog but in does not work. When dropping down, the focus moves to the input control but immediately get out from it,not allowing me to type anything.
This is the HTML:
<div id="asignar_servicio" title="Asignar servicios a usuarios">
<input type="hidden" class="bigdrop" id="a_per_id" />
</div>
And this is the javascript code:
$( "#asignar_servicio" ).dialog({
autoOpen: false,
height: 500,
width: 450,
modal: true,
buttons: {
"Cancelar": function () {
$('#asignar_servicio').dialog('close');
}
}
});
$("#a_per_id").select2({
placeholder: "Busque un funcionario",
width: 400,
minimumInputLength: 4,
ajax: {
url: "#Url.Action("Search", "Personal")",
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10,
};
},
results: function (data, page) {
return { results: data.results };
}
}
}).on("change", function (e) {
var texto = $('lista_personal_text').val().replace(/ /g, '');
if (texto != '')
texto += ',';
texto += e.added.text;
var ids = $('lista_personal_id').val().replace(/ /g, '');
if (ids != '')
ids += ',';
ids += e.added.id;
});
I have this same code in other page and it works.
Any help will be appreciated,
thanks
Jaime
jstuardo's link is good, but there's a lot to sift through on that page. Here's the code you need:
$.ui.dialog.prototype._allowInteraction = function(e) {
return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-drop').length;
};
Just add it next to wherever you are setting the select2 drop down.
An easy way:
$.ui.dialog.prototype._allowInteraction = function (e) {
return true;
};
add this after whereever you set select2
Or try this from:
Select2 doesn't work when embedded in a bootstrap modal
Remove tabindex="-1" from the modal div
I have found this workaround. https://github.com/ivaynberg/select2/issues/1246
Cheers
Jame
There's a new version of the fix for select2 4.0 from the github issue thread about this problem:
if ($.ui && $.ui.dialog && $.ui.dialog.prototype._allowInteraction) {
var ui_dialog_interaction = $.ui.dialog.prototype._allowInteraction;
$.ui.dialog.prototype._allowInteraction = function(e) {
if ($(e.target).closest('.select2-dropdown').length) return true;
return ui_dialog_interaction.apply(this, arguments);
};
}
Just run this before any modal dialogs that will have select2 in them are created.
JSFiddle of this fix in action
The best solution I found was just making the dialog not be a modal dialog by removing modal:true. Once you do this the page will function as desired.
After a while of battling with this I found another option that allows you to keep the dialog as a modal. If you modify the css for select2 to something like the following:
.select2-drop {
z-index: 1013;
}
.select2-results {
z-index: 999;
}
.select2-result {
z-index: 1010;
}
keep in mind that this works however if you open a lot of dialogs on the same page it will eventually exceed the z-index specified, however in my use case these numbers got the job done.
Not enough reputation to comment on a previous post, but I wanted to add this bit of code:
$('#dialogDiv').dialog({
title: "Create Dialog",
height: 410,
width: 530,
resizable: false,
draggable: false,
closeOnEscape: false,
//in order for select2 search to work "modal: true" cannot be present.
//modal: true,
position: "center",
open: function () { },
close: function () { $(this).dialog("distroy").remove(); }
});
$("#displaySelectTwo")select2();
Updating to the newer version of JQuery and Select2 is not an option in our application at this time. (using JQueryUI v1.8 and Select2 v1)
Add this after your select2() declaration.
$.ui.dialog.prototype._allowInteraction = function (e) {
return !!$(e.target).closest('.ui-dialog, .ui-datepicker, .select2-dropdown').length;
};
I've used the following fix with success:
$.fn.modal.Constructor.prototype.enforceFocus = function () {
var that = this;
$(document).on('focusin.modal', function (e) {
if ($(e.target).hasClass('select2-input')) {
return true;
}
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus();
}
});
}
I could fix this by removing the option: 'modal: true' from the dialog options.
It worked fine.
For anyone stumpling upon this with Select2 v4.0.12
I was using the Select2 option dropdownParent
i set the dropDownParent value, and still had the issue.
dropdownParent: $("#ReportFilterDialog")
What fixed it for me, was setting the value to, to select the outer layer of the modal dialog:
dropdownParent: $("#ReportFilterDialog").parent()

Resources