Set the initial value for select by selectize.js? - javascript

I want to display the initial value when initialized but it doesn't seem to work. I tried to research and found a way but couldn't.
HTML
<select class="select-links" multiple id="selectID">
<option value="KR" selected="selected">Koren</option>
</select>
JS
var select = $('.select-links').selectize({
valueField: 'url',
searchField: 'title',
plugins: ['remove_button'],
options: [],
render: {
option: function (data, escape) {
return '<div class="option">' +
'<span class="title">' + escape(data.title) + '</span>' +
'<span class="url">' + escape(data.url) + '</span>' +
'</div>';
},
item: function (data, escape) {
return '<div class="item">' + escape(data.title) + '</div>';
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "/account.json",
type: 'POST',
error: function () {
callback();
},
success: function (data) {
var Array_User = [];
for (var i = 0; i < data.array.length; i++) {
var obj = data.array[i];
Array_User.push({ id: obj.ID, name: obj.Full_Name, email: obj.Email });
}
callback(Array_User)
}
});
}
});

Related

Why is the data from the database not displayed in the select through ajax?

Good evening, I'm sorry, this text was translated through google translator
I'm not very good at parsing javascript, when I copy this code from the documentation, the data is successfully loaded and displayed
$("#select-repo").selectize({
valueField: "url",
labelField: "name",
searchField: "name",
create: false,
render: {
option: function (item, escape) {
return (
"<div>" +
'<span class="title">' +
'<span class="name"><i class="icon ' +
(item.fork ? "fork" : "source") +
'"></i>' +
escape(item.name) +
"</span>" +
'<span class="by">' +
escape(item.username) +
"</span>" +
"</span>" +
'<span class="description">' +
escape(item.description) +
"</span>" +
'<ul class="meta">' +
(item.language ? '<li class="language">' + escape(item.language) + "</li>" : "") +
'<li class="watchers"><span>' +
escape(item.watchers) +
"</span> watchers</li>" +
'<li class="forks"><span>' +
escape(item.forks) +
"</span> forks</li>" +
'<li class="stars"><span>' +
escape(item.followers) +
"</span> stars</li>" +
"</ul>" +
"</div>"
);
},
},
score: function (search) {
var score = this.getScoreFunction(search);
return function (item) {
return score(item) * (1 + Math.min(item.watchers / 100, 1));
};
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "https://api.github.com/legacy/repos/search/" + encodeURIComponent(query),
type: "GET",
error: function () {
callback();
},
success: function (res) {
callback(res.repositories.slice(0, 10));
},
});
},
});
But as soon as I change the data to my own, my code stops working
$(".add-items-select").selectize({
valueField: "id",
labelField: "name",
// searchField: "name",
create: true,
render: {
option: function (item, escape) {
return "<div>" + '<span class="title">' + escape(item.id) + "</span>" + "</div>";
},
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "http://127.0.0.1:8000/warehouse/api/products/" + encodeURIComponent(query)+ "/?format=json",
type: "GET",
error: function () {
callback();
},
success: function (res) {
callback(res);
callback(console.log(res));
},
});
},
});
Data is displayed in the console, but the render function does not work
Here is my json
{"id":1,"company_detail":{"id":1,"name":"test","adress":null},"articul":"1","name":"teyit","category_detail":null,"stock":0,"sell_price":"123.00","last_buy_price":"1.00","archived":false}

Jquery repeater with select2 not working properly

I am seaching from 2 days about this issue.
The first element is working perfectly. But after repeat the element, previous element's select2 fields destroyed automatically.
There is two rop divs in repeater. When first one selected by the ajax request I am appending the options to values section.
Here is the screenshot for reference.
Here is the code for repeater and select2 initialization.
<script>
$(function () {
$(".attribute_list").on('change', ".attribute", function (e) {
var attr_name = $(this).attr('name');
var attr_id = $(this).val();
$.ajax({
type: "POST",
url: "{{ route('products.getValue') }}",
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
contentType: "application/json",
dataType: "json",
data: '{"attr_id": "' + attr_id + '", "attr_name" : "' + attr_name + '"}',
success: function (data) {
var attribute_value = data.attribute_value;
var field_name = 'select[name="product_attribute[' + data.field_name + '][attribute_values][]"]';
if (attribute_value) {
$(field_name).empty();
$.each(attribute_value, function (key, value) {
$(field_name).append('<option value="' + value.id + '">' + value.value + '</option>');
});
// $(field_name).select2();
} else {
$(field_name).empty();
}
}
});
});
});
</script>
<script>
// $("#attribute_button").click(function(){
// $('#attribute_values').select2({
// placeholder: "select attribute value"
// });
// });
window.onload = function () {
$('.attribute_values').select2({
placeholder: "select attribute value",
allowClear: true
});
}
$('.repeater').repeater({
initEmpty: false,
show: function () {
$(this).slideDown();
$('.attribute_values').select2({
placeholder: "select attribute value"
});
},
hide: function (deleteElement) {
if (confirm('Are you sure you want to delete this element?')) {
$(this).slideUp(deleteElement);
}
},
ready: function (setIndexes) {
},
})

formatSelection not working in select2.js

I am using select2.js to populate the field with multiple values using ajax call.
Below is the code that I am using.
HTML
<input id="id_test_name" class="form-control">
Script
<script type="text/javascript">
$("#id_test_name").select2({
placeholder: "Search for an Item",
minimumInputLength: 2,
ajax: {
url: "/resourse/?format=json&name=xyz",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
option: term
};
},
results: function (data, page) {
return {
results: $.map(data.results, function (item) {
return {
name: item.name,
abbreviation: item.abbreviation,
id: item.id
}
})
};
}
},
formatResult: function (data, term) {
return data.name + '(' + data.abbreviation +')';
},
formatSelection: function (data) {
return data.name + '(' + data.abbreviation +')';
},
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) {
return m;
}
});
</script>
results are populating in dropdown but I am not able to select the populated results, I am not able to find what I am doing wrong?
Also I need the id of selected results in some other(hidden) field.
Update:
jsfiddle: http://jsfiddle.net/n5phohov/2
If you are using the current select2 v4, the parameters formatResult and formatTemplate were replaced by templateResult and templateSelection. Also you can call functions to format the results. Look the example bellow, observe that I used base64 image contained in a data attribute, you can easily replace for an image link matching with the option.
$('#combo').select2({
language : "pt-BR",
allowClear: true,
placeholder: "Selecione",
templateResult: formatSingleResult,
templateSelection: formatSelected
}).on('select2:select', function (e) {
var data = e.params.data;
let thumbnailValue='';
$(data.element.attributes).each( function (){
if ($(this)[0].name == 'data-thumbnail' ){
thumbnailValue = $(this)[0].value;
}
});
function formatSelected(state) {
let img='';
if (printImage == true){
img='<img src="' + $(state.element).attr('data-thumbnail') +'" class="comboImg"/>';
}
$item = $(`<span>${img} ${state.text.trim()}<span>`);
return $item;
}
function formatSingleResult (result) {
if (!result.id) {
return result.text.trim();
}
let img="";
if (printImage == true){
img='<img src="' + $(result.element).attr('data-thumbnail') +'" class="flag"/>';
}
const optionText = result.text.trim();
const $item = $(`<span>${img} ${optionText}<span>`);
return $item;
}

Jquery autocomplete - how modify returned data

I have code like this:
$(document).ready(function () {
if ($('#au').length <= 0) {
return;
}
var $project = $('#au');
$project.autocomplete({
minLength: 4,
source: function (request, response) {
$.ajax({
dataType: "json",
type: 'post',
cache: false,
data: {term: request.term},
url: '/Movies/ajax/',
success: function (data) {
if (isNaN($('#au').val())) {
response($.map(data, function (item) {
return {
label: item.Movies__name + " " + "(" + item.Movies__id + ")",
value: item.Movies__name
}
}));
} else {
response($.map(data, function (item) {
return {
label: item.Movies__id + " " + "(" + item.Movies__name + ")",
value: item.Movies__id
}
}));
}
}
});
},
select: function(event, ui) {
$("#au").val(ui.item.value);
$("#au").submit();
},
create: function (event, ui) {
},
open: function (event, ui) {
}
});
});
This code works fine. Basicly when You type in form "Alie", you will get
Alien(22)
Aliens2(32)
Aliens3(43)
Or when you type Id istead of movie name, you will get:
(22)Alien
(22)Other and so on....
So this code returns list of data - movie and id.
And now i want, to have first result without id, so when You type movie name like "Alie" you will get:
Alien
Alien(22)
Aliens(32)
First match without id.
Thanks for any replies.
response($.map(data, function (item, i) {
return {
label: item.Movies__name + (i != 0 ? " (" + item.Movies__id + ")" : ""),
value: item.Movies__name
}
}));
Use i for index in map function. If 0, you don't show id.

dynamically create radiobuttons and labels

Ok what I want to achieve is that it creates this automatically for each record I got back from my webservice.
<label for="ZAALID_1">Zaal 1</label>
<input id="ZAALID_1" type="radio" name="RESERVATIE.ZAALID" value="1" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,'1'),CHECKED,)~" />
I am calling this webservice with an ajax call. There is nothing wrong with this call. I tested it with printing down the values.
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
if (zalen.length > 0) {
$.each(zalen, function (index, zaal) {
createRadioElement(zaal.zaalId);
createLabel(zaal.zaalNaam,zaal.zaalId);
});
}
}
});
So I think there is an mistake in CreateRadioElement and createLabel.
Here are these two functions.
function createRadioElement( id ) {
var radioInput;
try {
var radioHtml = '<input id="ZAALID_' + id + '" type="radio" name="RESERVATION.ZAALID" value="' + id + '" MSGCHECKED="~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ';
radioHtml += '/>';
radioInput = document.createElement(radioHtml);
} catch( err ) {
radioInput = document.createElement('input');
radioInput.setAttribute('type', 'radio');
radioInput.setAttribute('name', 'RESERVATION.ZAALID');
}
return radioInput;
}
function createLabel(name,id) {
var label;
var labelHTML = '<label for="ZAALID_' + id + '">'+ name +'</label>';
label = document.createElement(labelHTML);
return label;
}
Now another thing that I want to do is that is places these radiobuttons inside the div with id=zaalField
here is the HTML of that div
<div id=ZaalField data-role="fieldcontain" class="knoppen_boven">
<LABEL for=zaal>Zalen ter beschikking: </LABEL>
//Here should go the radiobuttons and labels.
</div>
Can anybody help ?
Kind regards
---EDIT---
function getZalen()
{
var dateB = $("#DATUM_BEGIN").val();
var dateE = $("#DATUM_EINDE").val();
console.log(dateB);
$.ajax({
url: "~SYSTEM.URL~~CAMPAIGN.URL~/SelligentMobile/Webservice/WebService.asmx/getReservaties",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'DATUM_BEGIN':'2012-05-09 10:10:36','DATUM_EINDE':'2012-05-09 12:10:45'}",
success: function (response) {
var zalen = response.d;
alert(JSON.stringify(zalen));
if (zalen.length > 0) {
$.each(zalen, function (i, entity) {
$('ZaalField ').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
}
});
}
$(document).ready(function () {
var data = { "d": [{ "__type": "Reservatie", "zaalId": 2, "opmerking": null, "zaalNaam": "Zaal 2" }, { "__type": "Reservatie", "zaalId": 3, "opmerking": null, "zaalNaam": "Zaal 3"}] };
// $.ajax({
// url: "/SelligentMobile/Webservice/WebService.asmx/getReservaties",
// type: "POST", contentType: "application/json; charset=utf-8",
// dataType: "json", data: { 'DATUM_BEGIN': '2012-05-09 10:10:36', 'DATUM_EINDE': '2012-05-09 12:10:45' },
// success: function (data) {
if (data.d.length > 0) {
$.each(data.d, function (i, entity) {
$('body').append(
$('<label />', { 'for': 'ZAALID_' + entity.zaalId, 'text': entity.zaalNaam }),
$('<input />', { 'id': 'ZAALID_' + entity.zaalId, 'type': 'radio', 'name': 'RESERVATION.ZAALID', 'value': entity.zaalId, 'MSGCHECKED': '~IF(CHKPROP(#RESERVATIE.ZAALID,' + 1 + '),CHECKED,)~ ' }), $('<br />'));
});
}
// }
// });
});
function createLabel(id, name){
var name = "Zaal 2";
var label = document.createElement("label");
label.setAttribute("for","RANDOM"+id);
label.innerHTML = name;
return label;
}
var label = createLabel(2, "Zaal 2");
$(document.body).append(label); //add it to the body, or to whatever else you want to add it to.
This code works for me, while the code you have written doesn't.

Categories