Set Selected Value Remote Select2 With Configuration FormatSelection - jquery-select2

I have a problem that when i choose from Select, it will show option with formatSelection that i have configed BUT when i set selected value for Select that didn't get data object variable formatRepoSelectionLanguage from data_selection
function setSelect2Data(id, data_id = null, data_text = null, data_image = null, data_description = null, data_path = null, data_select = ""){
/*
id: selection class or ID of component has use Select2
data_id: id
data_text: text
data_image: image
data_path: path
data_description: description
data_select: String HTML Selection
*/
var data_selection = {
id : data_id||null,
text : data_text||null,
image : data_image||null,
path : data_path||null,
description: data_description||null
}
$(id)
.empty()
.append(data_select);
//$(id).select2('data' ,data_selection);
$(id).append(data_selection).trigger('change');
$(id).trigger({
type: 'select2:select',
params: {
object: data_selection,
formatSelection: formatRepoSelectionLanguage(data_selection),
formatResult: formatRepoLanguage(data_selection)
}
});
}
This is formatRepoLanguage:
function formatRepoLanguage (repo) {
if (repo.loading) {
return repo.text;
}
var $container = $(
"<div class='select2-result-language clearfix'>" +
"<div class='select2-result-language__icon'><img src='" + base_url_icon + repo.image + "' /></div>" +
"<div class='select2-result-language__meta'>" +
"<div class='select2-result-language__title'></div>" +
"<div class='select2-result-language__description'></div>" +
"</div>" +
"</div>"
);
$container.find(".select2-result-language__title").text(repo.text);
$container.find(".select2-result-language__description").text(repo.path)
return $container;
}
This is formatRepoSelectionLanguage:
function formatRepoSelectionLanguage (state) {
if (!state.id) {
return state.text;
}
var $state = $(
'<span id = "language_'+ state.id +'"><img class="img-flag" /> <span></span></span>'
);
// Use .text() instead of HTML string concatenation to avoid script injection issues
$state.find("span").text(state.text);
$state.find("img").attr("src", base_url_icon + state.image);
return $state;
}

I have try to set data like a string to option element and it works! Actually i think it's a bug of Select2 and i'm using version 4.0.13 and now i recognize that i don't need to use select2 function coz it takes data from option element which i have append into select element! That's my answer for my question if anyone have good idea please tell me! Thanks for your time!

Related

Get term for selected autocomplete when multiple are on one page

I have a page where I am adding jquery-ui autocompletes dynamically
My .autocomplete() code includes a $.getJSON('my_url', my_payload) where, in my_payload,' I am trying to send the request.term (what I typed into the jqueryui textbox) as well as the id of the jquery ui text box.
The problem is, for all the dynamically added textboxes, they were just picking up the term and id of the original autocomplete.
I managed to find a way to get the id of the added (not original) autocomplete by wrapping the autocomplete in a function that has the added field passed in as a parameter, but because the 'term' is in the request, which comes from .autocomplete, I do not know how to get this for the new ones.
https://jsfiddle.net/amchugh89/1L8jvea5/4/
//=======dynamic formset script from https://medium.com/all-about-
django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0======
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() {
if ($(this).attr('name')){
var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
if($(this).attr('id').includes('gl')){
console.log($(this).attr('id'))
make_autocomplete($(this))
}
}
});
newElement.find('label').each(function() {
var forValue = $(this).attr('for');
if (forValue) {
forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-');
$(this).attr({'for': forValue});
}
});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
var conditionRow = $('.form-row:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>');
return false;
}
function deleteForm(prefix, btn) {
var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (total > 1){
btn.closest('.form-row').remove();
var forms = $('.form-row');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).find(':input').each(function() {
updateElementIndex(this, prefix, i);
});
}
}
return false;
}
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
cloneMore('.form-row:last', 'form');
return false;
});
$(document).on('click', '.remove-form-row', function(e){
e.preventDefault();
deleteForm('form', $(this));
return false;
});
//====================
//AUTOCOMPLETE==(that allows for multiple ACs
https://stackoverflow.com/questions/24656589/using-jquery-ui-autocomplete-
with-multiple-input-fields)===================================
function make_autocomplete(ee) {
ee.on("focus", function(){ //.autocomplete({
$(this).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
//with the formset, I want to get the row for which I am typing in the
'term'
var this_formset_row_autocomplete_id
=ee.attr('id');//$(this.element).prop("id");//
$(this).attr('id');
console.log(this_formset_row_autocomplete_id);
var corresponding_branch_html_id =
this_formset_row_autocomplete_id.replace('gl_account','branch');
var this_formset_row_branch_sym_id =
$('#'+corresponding_branch_html_id).val();
//console.log(corresponding_branch_html_id, this_formset_row_branch_sym_id)
var appended_data={term:term,
this_formset_row_branch_sym_id:this_formset_row_branch_sym_id};
console.log(appended_data);
$.getJSON( "{% url 'dashapp:account_autocomplete' %}", appended_data,
function( data,
status, xhr ) {
//cache[ term ] = data;
response( data );
});
}
});
});
}//end function make_autocomplete
var ee =$( ".account_autocomplete" )
make_autocomplete(ee)
//===============
You may want to try to make it more simple for testing. Something like:
function make_autocomplete(obj) {
obj.autocomplete({
minLength: 2,
source: function(req, resp) {
var myData = {
term: req.term,
original_form_branch_id: $(this).closest("form").attr("id"),
this_formset_row_branch_sym_id: $(this).closest(".row").find("select").val()
}
$.getJSON("myurl", myData, function(results) {
resp(results);
});
}
});
}
Fiddle: https://jsfiddle.net/Twisty/pywb9nhv/23/
This uses .closest() to gather details from the relative objects. Also I do not see any benefit to initializing Autocomplete on focus event.
If you would like further help, please provide Example Data that can be used in a working example.
Hope that helps a little.

Updating tooltip with changed value from onCellValueChanged() event handler

I have set a 'tooltip' at columnDefs as below,
var columnDefs = [{
headerName: "City",
field: "city",
cellRenderer: function(params) {
return '<span title="'+params.value+'">'+params.value+'</span>';
},
editable: true
}
This tool tip is rendered properly on hover over the cells with the value in the cell.
Now I am also capturing the old and new values after a cell edit in onCellValueChanged() event handler as below,
onCellValueChanged: function(params) {
if (params.oldValue !== params.newValue) {
// Send the values to the tool tip
}
}
Is it possible to update my tool tip with the values captured in the onCellValueChanged() handler ? I mean, passing the params.oldValue and params.newValue() somehow to the 'tooltip' which is on my cellRenderer.
This issue is fixed, this demo updates tool tips when change occurs.
var oldValue = params.oldValue;
var newValue = params.newValue;
var recordKey = params.data.key;
var columnField = params.colDef.field;
if (!_.isEqual(oldValue, newValue)) {
if (!cellMetadata[recordKey]) {
cellMetadata[recordKey] = {};
}
if (!cellMetadata[recordKey][columnField]) {
cellMetadata[recordKey][columnField] = {};
}
cellMetadata[recordKey][columnField].trackChanges = true;
cellMetadata[recordKey][columnField].tooltip =
columnField.toUpperCase() + ' ' + 'Changed from' + ' ' + oldValue + ' ' + 'to' + ' ' + newValue;
}

in a jQuery Dynamic split button listview, how to get the value of HREF

i have created a dynamic jquery split button listview on a clickable button whose structure is something like this:
var Book="Book Item"
var data="hi";
//Create the listview if not created
if(!listCreated){
$("#content").append("<ul id='list' data-role='listview' data-inset='true'></ul>");
listCreated = true;
$("#content").trigger("create");
}
$("#list").append("<li data-theme='d'>"+"<a id='list_content' data-rel='popup' data-position-to='window' data-transition='pop'>"+data+"</a>"+"<a id='list_content_checkout' data-rel='popup' data-position-to='window' data-transition='pop'></a>"+"</li>");
$("#list").listview("refresh");
$("#list_content").click(function(){
alert();//
});
in given below line data is a variable whose value i want on list view click.
$("#list").append("<li data-theme='d'>"+"<a id='list_content' data-rel='popup' data-position-to='window' data-transition='pop'>"+data+"</a>"+"<a id='list_content_checkout' data-rel='popup' data-position-to='window' data-transition='pop'></a>"+"</li>");
when we click on ANKUR listview data, in alert ankur should come.
sorry for my english.
thanks
$(document).ready(function () {
Getdata();
});
function Getdata() {
var htmlcontent = "";
var strord_key = "1234";
htmlcontent += "<li data-role='list-divider'><br>";
htmlcontent += "<a href='javascript:void(0);' onclick= goToNext('" + strord_key + "') >Order Ticket: " + strord_key + "</a> </li>";
$("#result-listview").empty();
$('#result-listview').append(htmlcontent);
}
function goToNext(value) {
alert(value);
}

Breezejs Extending Entities

I have an issue with Breezejs (1.4.2) q (0.9.7)
I want to add a computed property for an entity.
var doctorInitializer = function (doctor) {
doctor.FullName = ko.computed(function () {
return doctor.FirstName() + " " + doctor.MiddleName() + " " + doctor.LastName() + " " + doctor.SurName();
});
};
var doctorName = '/breeze/polyclinic',
doctorManager = new breeze.EntityManager(doctorName);
var store = doctorManager.metadataStore;
store.registerEntityTypeCtor("Doctor", null, doctorInitializer);
i try adding a knockout computed to the constructor
var doctor = function () {
self.FullName = ko.computed( {
read: function() {
return self.FirstName + " " + self.MiddleName + " " + self.LastName + " " + self.SurName;
},
deferEvaluation: true
});
};
store.registerEntityTypeCtor("Doctor", doctorInitializer);
in both cases only work if i remove the parenthesis but MiddleName and SurName is not required and instead of empty string i got null
this is the error i have http://screencast.com/t/bP9Xnmf9Jm
UPDATE
I try adding the error on console log and follow your example and i have the same error is not a function http://screencast.com/t/bQTyV8XGD0Pk
doctor.FullName = ko.computed(function () {
var fullName = "";
fullName += doctor.FirstName();
if (doctor.FirstName()) {
fullName += ' ' + doctor.FirstName();
}
fullName += ' ' + doctor.LastName();
if (doctor.SurName()) {
fullName += ' ' + doctor.SurName();
}
return fullName;
});
var query = breeze.EntityQuery.from("Doctors").orderBy("Id")
doctorManager.executeQuery(query)
.then(function (data) {
self.doctors.removeAll();
self.doctors(data.results);
})
.fail(function(error) {
console.log(error);
});
I hope someone can help me
The error you are seeing in the screenshot is because your query is throwing an error that you are not handling. Attach a .fail(failFunction) on the end of your entityQuery.
You can't call doctor.Surname() if there is no Surname function that is attached. Calling doctor.Surname just returns a function that doesn't give you a value.
Odds are, you don't 100% get why it's not working because you don't understand how Knockout works. You probably don't yet understand the meaning of what I am describing above either. You need to understand how Knockout works first, then try to learn Breeze.
If you want to just make it work without understand how or why put this in there and continue on. This assumes that there is a property returned called MiddleName and SurName that are just empty.
doctor.FullName = ko.computed(function () {
var fullName = "";
fullName += doctor.FirstName();
if (doctor.MiddleName()) { fullName += ' ' + doctor.MiddleName(); }
fullName += ' ' + doctor.LastName();
if (doctor.SurName()) { fullName += ' ' + doctor.SurName(); }
return fullName
});

on() doesn't work with live data using jQuery, how to?

i have some dynamic data that gets appended to a list and any links in that data doesnt seem to work.
i am using jquery 1.8.3 and on() should account for the live method, i think
setInterval(function () {
getNot();
}, 2000);
function getNot() {
var data = {
t1: 'test1',
t2: 'test2',
t3: 'test3'
};
var size = 0,
li = '';
$.each(data, function (k, v) {
li += '<li>' +
'<a href="#" class="add" data-listid="' + k + '">' +
'<h2>load data - ' + k + '</h2>' +
'</a>' +
'</li>';
size++;
});
var but = $('#not'),
ul = $('#not_ul');
but.find('span').text(size + ' Notifications');
ul.html(li);
ul.listview().listview("refresh");
}
// this doesn't seem to work
$('.add').on("click", function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
see full example here
any ideas on this issue?
$('.add').on("click", function () {
You need to pass a selector to make on generate a delegate event:
$('#{containerId}').on("click", '.add', function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
containerId should be the closest static element to the dynamic created .adds elements.

Resources