Kendo Combo Box Scroll: automatically call function - javascript

I am new to Kendo and creating a project using it. I have encountered a very unique kind of problem. I am using select options in kendoCombox. What I am doing is that I am just updating the select box value on click of the edit button. The value is updated successfully but when I scroll, it automatically calls the function where I get all values. Here is my code:
I am updating the value using this:
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
<select class="span12" onchange="rackChange()" id="rackModelName" name="rackModelName"
tabindex="6">
</select>
The below function automatically calls on scroll change:
function getRackFun(libraryDeviceId,dataCenterId,type){
console.log("calling");
if(libraryDeviceId && dataCenterId){
$.ajax({
type : "GET",
dataType : "json",
url : "${getRacksByLocationId}&libraryDeviceId=" + libraryDeviceId+"&dataCenterId=" +dataCenterId,
success : function(result) {
if(result.length>0){
var jsonObject = jQuery.parseJSON(JSON.stringify(result));
$("#rackModelName").data("kendoComboBox").setDataSource(jsonObject);
}else{
if(type!="edit"){
$("#rackModelName").data("kendoComboBox").value("");
$("#rackModelName").val("");
$("#rackModelName").data("kendoComboBox").setDataSource([]);
$("#rackStartUnit").empty();
$("#rackStartUnit").append($('<option>',{
value : '',
text : '<liferay-ui:message key="inventory.please_select"></liferay-ui:message>'
}));
$("#rackEndUnit").val('');
}
}
}
});
}else{
$("#rackModelName").data("kendoComboBox").value("");
}
}

change the way you initialize the combobox to
$("#rackModelName").kendoComboBox({
...
change: rackChange, //your change function name
...
});
$("#rackModelName").data("kendoComboBox").value(deviceModelName);
remove the on change from the html element
To know more about events trigger check this https://demos.telerik.com/kendo-ui/combobox/events

Related

Dynamically check javascript value after database update

I am developing a dynamically generated and self updating form in ASP.NET MVC using javavascript, Jquery, JSON/Ajax calls.
Here is how I set up my view code from the controller. I loop through all available controls from the controller:
<ul>
#using (Html.BeginForm("Index", "WebMan", FormMethod.Post)) {
foreach (var row in Model.controls)
{
<li>
<label>#row.Name</label>
#if (row.ControlType == "STRING" || row.ControlType == COMMENT")
{
<input type="text" name="#row.Name" id="#row.NameID" value="#row.Value" data-original-value="#row.Value" class="form-control data-field" style="width: 300px"/>
}
else if (row.ControlType == "DDL")
{
<select name="#row.Name" id="#row.NameID" class="form-control data-field" value="#row.Value" data-original-value="#row.Value" style="width: 300px">
#foreach (var o in row.Options)
{
<option value="#o.Value">#o.Text</option>
}
</select>
}
</li>
}
<button type="submit">Update</button>
}
</ul>
(notice that I set the value to the value from the database and I also set the “data-original-value” to the value from the database as well)
I am using the “data-original-value” to check to see if the value has changed later.
I also set up a javascript timer that executes every 5 seconds. This timer is meant to “update” the page. (code for timer below)
var interval = setInterval(function () { Update(); }, 10000);
When the timer executes, we loop through each control in the “data-field” class. This allows me to check each dynamically generated control.
Basically, If a user has edited a control, I DO NOT want to update that control, I want to ignore it. I only want to update that specific control if a user has not changed the value. When a user changes the value, the current value != orig value (Data-original-value), so we set the field to yellow and ignore the database update code.
function Update() {
UpdateControls();
}
function UpdateControls() {
$(".data-field").each(function () {
var nameAttr = $(this).attr('name');
var id = $(this).attr('id');
var val = document.getElementById(id).value;
var origVal = $(this).data("original-value");
if (origVal == val) {
//user did not change control, update from database
var url = "/WebMan/UpdateControlsFromDB/";
$.ajax({
url: url,
data: { name: nameAttr },
cache: false,
type: "POST",
success: function (data) {
if (data != null) {
document.getElementById(id).setAttribute("data-original-value", data);
document.getElementById(id).value = data;
}
else {
alert(data);
}
},
error: function (response) {
alert("Issue updating the page controls from database");
}
});
}
else {
document.getElementById(id).style.backgroundColor = "yellow";
//user changed control, do not update control and change color
}
});
}
If no change, this ajax method in my controller is called:
[HttpPost]
public ActionResult UpdateControlsFromDB(string name)
{
var curValue= db.Setup.Where(x => x.Name == name).Select(x =>Value).FirstOrDefault();
return Json(curValue);
}
The code works correctly if a user modifies the field. It senses that the user modifies the code, and changes the field yellow.
The part that does not work correctly, is if the database updates the field. When the database first updates the field, it looks great. We set the “data-original-field” value to the value as well, to tell our code that is should not turn yellow and the user has not modified it.
But after another update, “value” and “original-value” do not match. The code document.getElementById(id).value somehow gets the OLD version of the control. It does not get the current value. So then on next loop, the values don’t match and we stop updating from DB and the control turns yellow.
My issue is that my code senses that the control value changed (database update) and turns it yellow, when I only want to turn the control yellow when a USER has changed the value in the control.
I only want to change the control and prevent updating from DB when the control has been modified by the user.
Thank you for any help.

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

how to validate dynamic created element in jquery without using plugin

here i have created dynamic elements after clicking its adding one row.but how to validate it without plugin.
var cnt = 1;
$("#anc_add").click(function() {
cnt++;
$("input[id=rows]").val(cnt);
$('#tbl1 tr').last().after('<tr><td><select name="'+cnt+'1" id="'+cnt+'1" class="Exp"><option value="0" >Select Expenses Type</option></select></td><td><textarea name="'+cnt+'2"></textarea></td><td><input type="text" name="'+cnt+'3" id="'+cnt+'3" onkeypress="return isNumberKey(event)"></td></tr>');
element_id=cnt+'1';/*alert(element_id);*/
$.ajax({
url: "../../modal/system_operator/get_companyexpenses_type.php",
dataType: "html",
type: 'POST',
success:function(json) {
var result = jQuery.parseJSON(json);
length=result.len;
/*alert(length);*/
for(k=1;k<=length;k++) {
$('#'+element_id+' option').last().after('<option value="'+eval("result.row"+k+".company_expenses_type_id")+'">'+eval("result.row"+k+".company_expenses_type")+'</option>');
}
$('select[name="'+element_id+'"]').rules('add', {required:true});
}
});
});
I assume by without plugin means you do not use jquery.validate or some other plugin to validate your input control values.
Then try the following snippet
$(document).on('blur','#form_id input,#form_id select', function(){
// write your validation logic here
});
The above code says that all (including dynamic) input,select controls within #form_id element will call the function on blur event.

How to load 2 lists based on 2 select boxes on change of first box

From the title, you can understand that this one is a bit complicated, but it really shouldn't be. I'm sure this is an easy fix, I just can't wrap my head around it.
I have select box A which populates select box B whose combined criteria populate list A and list B. When select box A changes, the appropriate info loads into select box B and the lists should also get populated. Currently the lists only get populated when select box B changes.
It's set up so that on page load the first box A/B combo's lists get loaded. I need to set it up so that when box A changes (and box B automatically changes) the lists get loaded for box A/B criteria.
What I believe is happening is that when I attempt to attach any sort of handler to box B (or box A really) it looks to the previously loaded info in box B instead of the newly loaded info from when box A changed. I need it to look at the new A/B combo.
I've tried all sorts of handlers, javascript, jQuery: .onChange, .load, .live, .focus, but I don't think anything will work unless it picks up the new value in box B instead of the old value. I tried all this in the document ready function in the javascript and also in the .jsp:
<span class="caption">Business Unit</span>
<select style="margin-bottom: 20px" onchange="loadRatingPlans()"
name="cde_bus_unit" id="cde_bus_unit">
<c:forEach items="${divisions}" var="division">
<option value="${division.cdeBusUnit}">${division.nmeBusUnit}
</option>
</c:forEach>
</select>
<span class="caption">Rating Plan</span>
<select style="margin-bottom: 20px" onchange="loadAvailableLimitInfo();
loadBURPLimitInfo()"
name="cde_rating_plan" id="cde_rating_plan">
<c:forEach items="${ratingPlans}" var="ratingPlan">
<option value="${ratingPlan.cdeRatingPlan}">${ratingPlan.nmeRatingPlan}
</option>
</c:forEach>
</select>
This successfully changes the LimitInfo (lists A and B) when box B is physically selected. How do I make it do the same when just list A changes? Please ask me if you have any questions!! Thanks!
Here is the code for the javascript:
//populate the Rating Plans box based on the Business Unit
function loadRatingPlans() {
var busUnit = $('select[name="cde_bus_unit"]').val();
$.ajax({
type : 'GET',
url : 'loadRatingPlans.do',
dataType : 'json',
data : {
busUnit : busUnit
},
success : function(data) {
console.log(data);
//get rid of old rating plans
$('[name=cde_rating_plan]').empty();
//load new rating plans
if (data != null) {
data.forEach(function(rp) {
$('<option>').text(rp.nmeRatingPlan).val(rp.cdeRatingPlan)
.appendTo('[name=cde_rating_plan]');
}); // end forEach
}// end if
} // end success
});// end ajax
}// end uploadRatingPlans
//load the available limits based on which are already assigned
function loadAvailableLimitInfo() {
var cdeBusUnit = $('#cde_bus_unit').val();
var cdeRatingPlan = $('#cde_rating_plan').val();
$.ajax({
type : 'GET',
url : 'loadAvailableLimitInfo.do',
dataType : 'json',
data : {
cdeBusUnit : cdeBusUnit,
cdeRatingPlan : cdeRatingPlan
},
success : function(data) {
console.log(data);
$('#limAvailable').empty();
var i;
for (i = 0; i < data.length; i++){
$('#limAvailable').append('<li class="limit-list" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAvailable').append('\n');
}
} // end success
});// end ajax
}// end loadDivisionInfo
//load the assigned limits
function loadBURPLimitInfo() {
var cdeBusUnit = $('#cde_bus_unit').val();
var cdeRatingPlan = $('#cde_rating_plan').val();
$.ajax({
type : 'GET',
url : 'loadBURPLimitInfo.do',
dataType : 'json',
data : {
cdeBusUnit : cdeBusUnit,
cdeRatingPlan : cdeRatingPlan
},
success : function(data) {
console.log(data);
$('#limAssigned').empty();
var i;
for (i = 0; i < data.length; i++){
if(data[i].indDefault = -1){
$('#limAssigned').append('<li class="limit-list,
assigned-li-default" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAssigned').append('\n');
}
else{
$('#limAssigned').append('<li class="limit-list" id="'
+ data[i].cdeLimit + '">' + data[i].nmeLimit + '</li>');
$('#limAssigned').append('\n');
}
}
} // end success
});// end ajax
I worked it out. The answer is to create a method that will return the lists based on just the value of the first box. I go to the db and grab the value of the list for the second box and then return the lists based on the first value in that second list. I already had a method set up to do this for loading the lists based on the first set of values from the first and second boxes on the page load.

Ckeditor Dialog for building a Url from a user selected options from a JSON Dataset

I'm trying to use CKeditor as part of a CMS but I'm not "that" good with JavaScript and there documentation does not help much.
rather confusing could some one show me how I would change the link plugin dialog so that it shows a drop down of values and builds a URL from them, but I don't under stand how there dialog system works I have narrowed it down, i know that I will need to use the _sources/plugins/link/dialogs/link.js but as to how I am to a lost when working with this I just can't understand it.
Can some one show me the code i would need to add a Dropdown (select) to the dialog that has the options that then writes the value into the url Field E.G
My Server System has the URL /content/getLinks/ and this will return the CMS Pages like so,
[
{"page_name":"Contact Us","url":"Contact_Us","page_id":"1"},
{"page_name":"Welcome to Doxie Promotions","url":"Welcome_to_Doxie_Promotions","page_id":"2"},
{"page_name":"Bands","url":"Bands","page_id":"3"},
{"page_name":"Upcoming Events","url":"Upcoming_Events","page_id":"4"},
{"page_name":"About","url":"About","page_id":"7"},
{"page_name":"Lost Efftect","url":"Lost_Efftect","page_id":"10"}
]
Now from this data i want to build a select box like this
<select>
<option value="Contact_Us:1">Contact Us</option>
<option value="Welcome_to_Doxie_Promotions:1">Welcome to Doxie Promotions</option>
<option value="Bands:1">Bands</option>
<option value="Upcoming_Events:1">Upcoming Events</option>
<option value="About:1">About</option>
<option value="Lost_Efftect:1">Lost Efftect</option>
</select>
Then when one is selected I want the URL field to be changed E.G if the first was option selected the url would be
/content/load/pid/1/url/Contact_Us
I'm aware that i will need to copy the sources version of the plugin dialog over the standard one that has been min'ed
Update what I have tried so far
using _sources/plugins/link/dialogs/link.js and overwriting the plugins/link/dialogs/link.js
I have built this code
into the file at line 429
,
{
type : 'select',
id : 'cms_links',
label : 'CMS Page',
items:[],
onLoad : function(){
(function($){
$.ajax({
url: "/content/getLinks/",
dataType: 'json',
data: "",
success: function(data){
$.each(data, function(key, val){
$("#cms_links").append(
"<option value='"+val.url+":"+val.page_id+"'>"+val.page_name+"</option>"
);
});
}
});
})(jQuery);
}
},
but there is not even a select box drawn for the code that i have added so i'm still at a loss
You can try to use this plugin: http://cksource.com/forums/viewtopic.php?f=18&t=24282
To do this you have to have the de-minimized version of the code this is in the _sources at path _sources/plugins/link/dialogs/link.js copy this over top of the minimized code at plugins/link/dialogs/link.js i added the code below around line 429
,
{
type : 'select',
id : 'cms_links',
label : 'CMS Page',
class : 'cms_links',
items:[],
onLoad : function(){
(function($){
var cms_pageSelectElement;
var protocolSelectElement;
var urlSelectElement;
$.ajax({
url: "/content/getLinks/",
dataType: 'json',
success: function(data){
$("label").each(function(){
var value = $(this).html();
if(value == "CMS Page"){
cms_pageSelectElement = $(".cke_dialog_ui_input_select", $(this).parent());
console.log(cms_pageSelectElement);
}
if(value == "Protocol"){
protocolSelectElement = $(".cke_dialog_ui_input_select", $(this).parent());
console.log(protocolSelectElement);
}
if(value == "URL"){
urlSelectElement = $(".cke_dialog_ui_input_text", $(this).parent());
console.log(urlSelectElement);
}
});
$(cms_pageSelectElement).append("<option selected='selected'><none CMS link></option>");
for(var key in data){
var val = data[key];
$(cms_pageSelectElement).append(
"<option value='"+val.url+":"+val.page_id+"'>"+val.page_name+"</option>"
);
}
$(cms_pageSelectElement).change(function(){
var val = $(this).val();
var parts = val.split(":");
var url = "content/load/pid/"+parts[1]+"/url/"+parts[0];
$(urlSelectElement).val(url);
});
}
});
})(jQuery);
}
},
you have to exploit the system slightly to update the other elements when using jQuery as there are no values you can set that are then set on to the HTML elements so you have to hack around by selecting the label then getting the input from the parent of the label
I can give you this to start of: http://jsfiddle.net/VGWPL/

Categories

Resources