Passing DropdownList value inside grid to the grid itself - javascript

I've defined a DropdownList inside a KendoGrid. The DropdownList it's in a column on that Grid and it's showing the fields that come from the datasource correctly but, when I select one of those fields in the dropdown, it isnt passing/updating it's value to the grid itself.
I know that I need to use the change event to pass the value there but am not being able to do that somehow.
Can you help? I'll drop an image with the current code.
Thank you for the help.
if ('#viewMode.ToUpper()' == "EDIT") {
var grid = e.sender;
var items = e.sender.items();
items.each(function (e) {
var dataItem = grid.dataItem(this);
var promtypedropdown = $(this).find('.equipDropDownEditor');
$(promtypedropdown).kendoDropDownList({
dataTextField: "Text",
dataValueField: "Value",
dataSource: {
transport: {
read: {
dataType: "json",
url: '#Url.Action("GetPromoTypesCodeDetail", "Omni")'
}
},
width: 150,
schema: {
data: function (response) {
return response.data.data;
},
}
},
change: function(e){
var uid = $(e.sender.element).closest("tr").attr('data-uid');
var model = $("#omniDataGrid").data("kendoGrid").dataSource.getByUid(uid);
model.PROMOTION_TYPE = this.text();

For the future, I got it working adding the this line of code:
model.set("PROMOTION_TYPE", this.text());

Related

How to make datatable specific column editable?

There are various questions put up on this topic but I do not understand them so can anyone help
here is my js code
$(document).ready(function () {
$('#myModal').toggle();
var List = [];
$.ajax({
url: '/urls/' + id,
type: 'POST',
dataType: "json",
data: 'data',
success: function (data) {
console.log("data length: ", data.length);
console.log("data : ", data);
for (var i = 0; i < data.length; i++) {
var Logs = {};
Logs.Info = data[i].Info;
for (var j = 0; j < Logs.Info.length; j++) {
var emplist = {};
emplist.Name = Logs.Info[j].Name;
emplist.dates = Logs.Info[j].dates;
for (var k = 0; k < emplist.dates.length; k++) {
var datelist = {};
datelist.Name = emplist.Name;
datelist.startDate = emplist.dates[k].startDate;
datelist.endDate = emplist.dates[k].endDate;
List.push(datelist);
}
}
}
emptablee = $('#Table').DataTable({
"data": List,
"columns": [
{"data": "Name"},
{"data": "startDate"},
{"data": "endDate"},
],
destroy: true,
"scrollY": "200px",
"scrollCollapse": true,
"paging": false
});
/*emptablee.destroy();*/
}
});
$("#close").on('click', function () {
$("#myModal").hide();
});
});
There are three columns in the table and I want to make a specific columns cell-like editable and show an input box and get the value edited to send.
For anyone checking this now, I've created a custom example in which you can make any column editable by just sending it in a metadata request from serverside.
here : https://github.com/sinhashubh/datatable-examples
If you want, for example, your startDate column to be editable, you need to init the Datatables like this so you can hit the column by class name:
{"data": "startDate", "className": "editable"},
then, with proper event handling
// Activate an inline edit on click of a table cell
$('#Table').on( 'click', 'tbody td.editable', function (e) {
editor.inline( this );
} );
and initializing Editor you will be good:
editor = new $.fn.dataTable.Editor( {
ajax: "../ajax/handle-data.php", // path to back-end data handling
table: "#Table",
fields: [ {
label: "Start Date:",
name: "startDate"
}
]
} );
Also, don't forget to add this outside of document ready handler because you need it as a global var:
var editor;
Full example here (note that Datatables Editor feature is not free) https://editor.datatables.net/examples/inline-editing/columns.html
You can also code up your own completely free version, which is slightly more complicated, without using Editor, but still using class names so you can trigger on click events for specific columns.

Using jQuery to populate a DropDownList with items and their optgroups

I am still learning jQuery/json and am struggling to figure out how to include optgroups when building my DropDownList via jQuery using json data.
Here is an example of the json data:
0:
Disabled: false
Group:
Disabled: false
Name: "Property Overview"
Selected: false
Text: "Number of Floors"
Value: "277"
Currently, I am able to populate the DropDownList with the Text and Value. That is fairly straight forward. Here is my code for that:
$(document).ready(function () {
$("#PropertyList").on('change', function () {
$("#Options_Question").empty();
var id = $("#PropertyList").val();
var url = '#Url.Action("GetPropertyTypeSpecificQuestions", "Report", new { id = "replaceToken" })';
url = url.replace("replaceToken", id);
$.getJSON(url, null, function (data) {
$("#Options_Question").addQuestions(data);
});
});
$.fn.addQuestions = function (data) {
return this.each(function () {
var list = this;
$.each(data, function (index, questionData) {
var option = new Option(questionData.Text, questionData.Value);
list.add(option);
});
});
}
});
How can I edit my jQuery to include the values from Group.Name and group the questions into their respective optgroups?
I was able to get this working using information found in various places around stackoverflow. Here is the working jQuery:
$(document).ready(function () {
$("#PropertyList").on('change', function () {
$("#Options_Question").empty();
var id = $("#PropertyList").val();
var url = '#Url.Action("GetPropertyTypeSpecificQuestions", "Report", new { id = "replaceToken" })';
url = url.replace("replaceToken", id);
$.getJSON(url, null, function (data) {
$("#Options_Question").addQuestions(data);
});
});
$.fn.addQuestions = function (data) {
var prevGroup, prevGroupName;
$.each(data, function () {
if (this.Group.Name == null) {
$("<option />").val(this.Value).text(this.Text).appendTo("#Options_Question");
}
else if (prevGroupName != this.Group.Name) {
prevGroup = $('<optgroup />').prop('label', this.Group.Name).appendTo('#Options_Question');
}
$("<option />").val(this.Value).text(this.Text).appendTo(prevGroup);
prevGroupName = this.Group.Name;
});
}
});

Issue with setting value to select dropdown in MVC

I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();

DropDownList Children Binding

I have an issue with a dropdownlist and I can't figure it out how to solve it.
There are two different way to get into my view: Add New and Edit.
1) Add New: In this situation my dropdownlist is related to another one, and everything works great.
the dropdownlist is locked and empty until I select something in the other one.
2) Edit: In this situation my dropdownlist is already binded using stored data. Of course if I change the selected item in the "parent" one I want to change data to the children too.
The problem appears in the 2 case: When I select something else out of the stored data in the related dropdownlist.
It binds the correct data, but it gives an empty item as first, and not the first of the data.
How can I solve it?
<%=Html.Kendo().DropDownListFor(model => model.GNR_FK)
.Name("GNR_FK") .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Customer"])
.DataTextField("descriptionText")
.DataValueField("valueID")
.Value(Model.GNR_FK.ToString())
.Events(e =>
{
e.Select("onSelect");
})
%>
<%=Html.Kendo().DropDownListFor(model => model.CNT_FK) .BindTo((IEnumerable<Models.Widget.Combo>)ViewData["Sender"])
.Name("CNT_FK")
.DataTextField("descriptionText")
.DataValueField("valueID")
%>
Condition:
if (Model.PK == 0)
{
loadValues(current);
}
else
{
loadEditValues(current);
}
public JsonResult loadValues(Models.Model current, int PK = 0)
{
IDataReader sender = Model.getSender(PK);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
}
return Json(receiveSender, JsonRequestBehavior.AllowGet);
}
private void loadEditValues(Models.Model current)
{
int selected = current.GNR_FK;
IDataReader sender = current.getSender(selectedCustomer);
Models.Widget.Combo SenderNA = new Models.Widget.Combo();
List<Models.Widget.Combo> receiveSender = new List<Models.Widget.Combo>();
SenderNA.valueID = 0;
SenderNA.descriptionText = "NA";
receiveSender.Add(SenderNA);
while (sender.Read())
{
Models.Widget.Combo newItem = new Models.Widget.Combo();
newItem.valueID = int.Parse(sender["PK"].ToString());
newItem.descriptionText = sender["SURNAME"].ToString();
receiveSender.Add(newListItem);
ViewData["List"] = receiveSender;
}
}
Script:
function onSelect(e) {
var dataItem = this.dataItem(e.item);
var PK = dataItem.valueID;
$.ajax({
type: 'POST',
url: '/Project/loadValues',
data: "{'PK':'" + PK + "'}",
contentType: 'application/json; charset=utf-8',
success: function (result) {
$("#CNT_FK").data("kendoDropDownList").dataSource.data(result);
},
error: function (err, result) {
alert("Error" + err.responseText);
}
});
}
Regards
Problem Solved!
It was missing the select method to automatically select the first item after changing data!
success: function (result) {
var dropdown = $("#CNT_FK").data("kendoDropDownList");
dropdown.dataSource.data(result);
dropdown.select(0);
},

Update row in WebGrid with JQuery

FOUND THE PROBLEM:
Just needed to replace row.replaceWith with row.parent().parent().replaceWith().
I'm trying to update a WebGrid row with JQuery after I've clicked a submit button in a modal dialog, but the updated data just append the last column, not the whole row as I want.
Let's say I want the table to look like this after the update:
ID - Name - Phone number
But with my code it looks like this after the update:
ID - Name - ID - Name - Phone number
as it just replaces the last column with a new table within the last column with the updated data.
I'm getting the correct data as output, but in the wrong place in the row.
Please help! :)
Here is the Javascript code:
$(function () {
$("#edit-event-dialog").dialog({
resizable: false,
height: 300,
modal: true,
autoOpen: false,
open: function (event, ui) {
var objectid = $(this).data('id');
$('#edit-event-dialog').load("/Events/CreateEditPartial", { id: objectid });
},
buttons: {
"Save": function () {
var ai = {
EventID: $(this).data('id'),
Name: $("#Name").val(),
Phone: $("#Phone").val()
};
var json = $.toJSON(ai);
var row = $(this).data('row');
$.ajax({
url: $(this).data('url'),
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
var grid = $(".pretty-table");
row.replaceWith('<tr><td>' + data.ev.EventID + '</td><td>' +
data.ev.Name + '</td><td>' + data.ev.Phone + '</td></tr>');
},
error: function (data) {
var data = data;
alert("Error");
}
});
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this);
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row)
.dialog('open');
event.stopPropagation();
return true;
});
You have set row to $(this) which is your case represents $("#event-edit-btn") ( btw i suggest using classes as identifiers, but it's not a problem ). Later on you replace your actual button with the new <tr> set but what you actually need to do is traverse to the tr parent of that button and replace it.
Change your live handler to:
$("#event-edit-btn").live("click", function () {
var url = $(this).attr('controller');
var row = $(this).closest('tr'); //or use some #id or .class assigned to that element
var id = $(this).attr('objectid');
$("#edit-event-dialog")
.data('id', id)
.data('url', url)
.data('row', row )
.dialog('open');
event.stopPropagation();
return true;
});

Categories

Resources