I'm using selectize.js for remote search and get options against that search for my select input.
I've seen example code in their demo
<script type="application/javascript">
$(function () {
$('#workers_paid').selectize({
placeholder: "No worker Is selected",
valueField: "name",
labelfield : "name",
searchField: 'name',
render: {
option: function (item,escape) {
console.log(item);
}
},
onLoad : function (data) {
}
,
load: function (query, callback) {
alert(query);
let data = JSON.parse('{"users" : [{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"},{"user_name": "Humza"}]}');
callback(data.users);
}
});
});
</script>
This is my code that i've written for loading a static data but still render is not logging any data in console .... Onload function is also working just render is not calling anything or any options is not being created.
Sorry for bad english and thanks in advance
Related
I have been pretty much beginner at this part of javascript and I would appreciate any ideas how could be solved this problem.
I use requirejs to define my own modules where I also use backbone.js.
Let say I have the main module where I initialize my Backbone view which is rendered without any problem. Also, the click event where is calling method createSchemeForm creates the form correctly. The problem raises up in a situation when I call cancel method by click and the modules which are defined for Backbone view (e.g. "unicorn/sla/dom/helper"...) are undefined but when I called method createSchemeForm at the beginning the modules were executed without any problem.
Thank you in advance for any suggestions.
Backbone view
define("unicorn/sla/view/scheme", [
"unicorn/sla/dom/helper",
"unicorn/soy/utils",
"unicorn/sla/utils"
], function (DOMHelper, soyUtils, jsUtils) {
return Backbone.View.extend({
el: 'body',
inputData: {},
btnSaveScheme: 'btn-save-sla-scheme',
btnCancel: 'btn-cancel-sla-scheme',
btnCreate: 'btn-create-sla-scheme',
btnContainer: '#sla-scheme-buttons-container',
schemeContent: '#sla-scheme-content-section',
btnSpinner: '.button-spinner',
events: {
'click #btn-create-sla-scheme' : "createSchemeForm",
'click #btn-cancel-sla-scheme' : "cancel"
},
initialize: function(){
console.log("The scheme view is initialized...");
this.render();
},
createSchemeForm: function () {
this.spin();
DOMHelper.clearSchemeContent();
DOMHelper.clearButtonsContainer();
//Get button
$btnSave = soyUtils.getButton({isPrimary: 'true', id: this.btnSaveScheme, label: 'Save'});
$btnCancel = soyUtils.getButton({isPrimary: 'false', id: this.btnCancel, label: 'Cancel'});
//Append new created buttons
DOMHelper.addContent(this.btnContainer, AJS.format("{0}{1}", $btnSave, $btnCancel));
//Call service to get entry data for scheme creation form
AJS.$.ajax({
url: AJS.format('{0}={1}',AJS.I18n.getText('rest-url-project-scheme-input-data'), jsUtils.getProjectKey()) ,
type: "post",
async: false,
context: this,
global: false,
}).done(function (data) {
this.inputData = data;
$slaSchemeForm = soyUtils.getSchemeCreateForm({slaScheme : data, helpText: AJS.I18n.getText("sla-time-target-tooltip-text")});
DOMHelper.addContent(this.schemeContent, $slaSchemeForm);
jsUtils.scroll(this.schemeContent, 'slow');
}).fail(function () {
jsUtils.callFlag('error', AJS.I18n.getText("message-title-error"), AJS.I18n.getText("sla-error-load-scheme-input-data"));
}).always(function () {
this.stopSpin();
});
},
spin: function () {
AJS.$('.button-spinner').spin();
},
stopSpin: function () {
AJS.$('.button-spinner').spinStop();
},
cancel: function () {
jsUtils.clearButtonsContainer();
jsUtils.clearSchemeContent();
$btnCreateScheme = soyUtils.getButton({isPrimary: 'false', id: this.btnCreate, label: 'Create SLA Scheme'});
DOMHelper.addContent(this.btnContainer, $btnCreateScheme);
DOMHelper.addContent(this.schemeContent, soyUtils.getSchemesTable(new Array())); // TODO - get current data from server instead of empty array
}
});
});
Main module where is Backbone view initialize
define("unicorn/sla/project/batch", [
"unicorn/sla/utils",
"unicorn/sla/data/operations",
"unicorn/sla/data/validator",
"unicorn/sla/dom/helper",
"unicorn/sla/model/confirm/message",
"unicorn/sla/view/scheme",
"exports"
], function (jsUtils, operations, validator, DOMHelper, ConfirmMessage, SchemeView, exports) {
//Load project batch
exports.onReady = function () {
$schemeView = new SchemeView();
$schemeView.render();
}
});
AJS.$(function () {
AJS.$(document).ready(function () {
require("unicorn/sla/project/batch").onReady();
});
});
In my mvc view I have a DropDownList that gets values from a dictionary
<div class="InputPart">
#(Html.Telerik().DropDownListFor(model => model.PasportAddressRegionID)
.Name("ddlfRegions1")
.BindTo(new SelectList((IEnumerable<Dictionary>)ViewData["Regions"], "ID", "Title"))
.ClientEvents(e => e.OnChange("changeRegion1"))
.HtmlAttributes(new { style = "min-width:200px" }))
</div>
and I have JS function changeRegion1() that gets these values.
<script type="text/javascript">
function changeRegion1() {
var rgnId = $('#ddlfRegions1').data('tDropDownList').value();
$.ajax({
url: '#(Url.Action("_GetDistrict", "Staffs"))',
data: { regionId: rgnId },
type: "POST",
success: function (result) {
var combobox = $('#ddlfDistricts1').data('tDropDownList');
combobox.dataBind(result);
combobox.enable();
}
});
} </script>
I put the function in the same view, below all the code, but when run I got Uncaught ReferenceError: changeRegion1 is not defined. The function itself is OK, but it seems to me that event handler does not see it here.
So I just wonder what is wrong here? And how should I reference the function?
Any help is appreciated
Here is an example for the Kendu UI Dropdown list Event handling for ASP.Net and MVC. Compare to your code. The example shows Events, you call ClientEvents otherwise looks ok.
http://docs.telerik.com/aspnet-mvc/helpers/dropdownlist/overview
#(Html.Kendo().DropDownList()
.Name("dropdownlist")
.BindTo(new string[] { "Item1", "Item2", "Item3" })
.Events(e => e
.Select("dropdownlist_select")
.Change("dropdownlist_change")
)
)
<script>
function dropdownlist_select() {
//Handle the select event.
}
function dropdownlist_change() {
//Handle the change event.
}
The Problem
So i am currently trying to implement a color picker inside of a Kendo grid, that will hopefully send the chosen color to my Sql Table. Unfortunately, It doesn't seem as though the Update controller is being reached. I am relatively new to Kendo UI, so there might be some incredibly dumb errors shown.
Questions
I guess my main question would be: How can i call the update method when update is clicked on the grid. Essentially, the color picker and the edit command are showing up in beautiful fashion. I just want to know how i can be sure that the method is being called when 'Update' is clicked, seeing as it is not reaching my controller. Feel free to ask if you need to see more code or perhaps a screen shot.
Code
Config.cshtml ( Grid )
#model IEnumerable<STZN.Models.AGCData.ErrorCode>
#{
ViewBag.Title = "Config";
}
#section HeadContent{
<script src="~/Scripts/common.js"></script>
<script>
$(document).ready(function () {
$("#grid").kendoGrid({
editable: "inline",
selectable: "row",
dataSource: {
schema: {
model: {
id: "error_code",
fields: {
color: { type: 'string' }
}
}
},
transport: {
read: {
type: "POST",
dataType: "json",
url: "#Url.Action("ErrorCodes")"
},
update: {
type: "POST" ,
dataType: "json",
url: "#Url.Action("UpdateErrorCodes")",
}
}
},
columns: [
{ command : [ "edit" ] },
{
field: "error_code", title: "Error Code",
},
{
field: "error_description", title: "Error Description"
},
{
field: "color",
width: 150,
title: "Color",
template: function (dataItem) {
return "<div style = 'background-color: " + dataItem.color + ";' </div>"
},
editor: function (container, options) {
var input = $("<input/>");
input.attr("color",options.field);
input.appendTo(container);
input.kendoColorPicker({
value: options.model.color,
buttons: false
})
},
}
]
});
});
</script>
}
Update Controller
public JsonResult UpdateErrorCodes(ErrorCode model)
{
using (var db = new AgcDBEntities())
{
db.Entry(model).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
db.Configuration.ProxyCreationEnabled = false;
var data = db.ErrorCodes.Where(d => d.error_code == model.error_code).Select(x => new
{
error_code = x.error_code,
description = x.error_description,
color = x.color,
});
return new JsonResult()
{
JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet,
};
}
}
I actually managed to fix my issue by adding an additional input attribute to my editor function in the "color" field. It looks like this:
input.attr("data-bind","value:" + options.field);
There are still some present issues (unrelated to the fix/server update) , but as far as updating to the server, It work's as intended.
I am using paramquery grid component in which I am trying to use autocomplete.
Column Model for branch:
{ title: "Branch", dataIndx: "branchId", width: 150,
filter: { type: "select",
condition: 'equal',
prepend: { '': '--All--' },
listeners: ['change'],
valueIndx: "branchId",
labelIndx: "branchName",
options: branchList,
},
editor: {
type: "textbox",
init: autoCompleteEditor
//type: function (ui) { return dropdowneditor(this, ui); }
},
render: function (ui) {
for (var i = 0; i < branchList.length; i++) {
var option = branchList[i];
if (option.branchId == ui.rowData.branchId) {
return option.branchName;
}
}
}
}
autoCompleteEditorMethod:
var autoCompleteEditor = function (ui) {
var $inp = ui.$cell.find("input");
//initialize the editor
$inp.autocomplete({
source: function(request, response) {
var rows = imAutocompleteJSONParse(branchList);// this method converting my JSON object into Value and label format.
return response(rows);
},
selectItem: { on: true }, //custom option
highlightText: { on: true }, //custom option
minLength: 0,
select: function(event, ui) {
event.preventDefault();
$(this).val(ui.item.label);
},
focus: function(event, ui) {
event.preventDefault();
$("#search").val(ui.item.label);
}
}).focus(function () {
//open the autocomplete upon focus
$(this).autocomplete("search", "");
});
}
I get branch id into my grid and I have branchList JSON which have branch id & branch Name. Inside grid my render function showing branchName on UI.
But when I click on searchable dropdown I'm getting branch id.
Below snapshot may explain my issue properly.
Summary of issue: I am getting branch id in Grid. With help of render method I am able to show branch name on grid. but when I click on textbox I getting branch id.
http://jsfiddle.net/v4zx8tjc/4/
Like blackmiaool suggests in his comment, this question would be easier to answer with a live demo using something like JSFiddle.
Based on what I can see in your question, which isn't that much, there are a few areas I would take a second look at.
The Source function in JQuery.autoComplete. Where is branchList coming from? I don't see it declared anywhere and why are you not using the 'request' param?
Not sure what your custom properties are doing but it might be a good idea to verify those are not interfering with the results.
Edit 1: Looking back at the code you posted I think I see where your branchList variable is coming from. It would be very helpful to see your imAutocompleteJSONParse() method because I believe that may be where things are breaking down.
In the previous versions one can easily get this done by:
someDynamicData=function(){
//return some data...
}
$("#lga").select2({
width: '100%',
allowClear: false, placeholder: "--- please select ---",
data: function () {
return {results: someDynamicData, text: 'name'};
}
});
I this dosen't work with the new select2 v4. How do I achieve this in the new select2 v4.
For anyone that might be stocked as much as I am with select2 v4. I got a workaroud. Please note that I am some javascript guru and there might be some better way around this issue. For the time being this is rocking:
Case study: I have a chained select options which share from a list JSON Objects: here I am show only Subject and Level example just to keep it simple. When a Subject is selected I what to initialize the Level data source from the selected Subject's data source
function getDynamicData(){
return [
{"code": "ACC", "name": "ACCOUNTING", "levels": [
{"id": 3, "name": "SS 1", "description": "Senior Secondary School 1", "type": "Standard", "resultTemplates": []},
....
]}
....
];
}
$.fn.select2.amd.require(['select2/data/array', 'select2/utils'],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
subjects = getDynamicData();
$.map(subjects, function (d) {//Required only when the object do not have either id/text
d.id = d.code;
d.text = d.name;
return d;
});
callback({results: subjects});
};
$("#subjects").select2({
width: '100%',
dataAdapter: CustomData
});
}
);
This works fine but then I realized that I am repeating many things hence it is time for cleanup
//Added this function to a javascript file on my template (shared across pages)
function initMySelect2(myQuery, mySelector, props) {
$.fn.select2.amd.require(['select2/data/array', 'select2/utils'],
function (ArrayData, Utils) {
function CustomData($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
}
Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = myQuery;//Pass the query function as a parameter
$(mySelector).select2(props(CustomData));//Initialise the select2 with the custom data
}
);
}
//Used this to initialize select2
initMySelect2(function (params, callback) {
callback({results: getDynamicData()});
},
"#subjects",
function (myCustomData) {
return {
width: '100%',
placeholder: '---please select subjects ---',
dataAdapter: myCustomData
};
}
);
Reference https://select2.github.io/announcements-4.0.html
I hope this will help someone out there.