add new values to exsting variable in jquery - jquery-ui

i have a variable in jquery. first am adding some values to it.
now again am adding some more values to existing variable.
here is my code. if any one know help me......
var eventToAdd = {
title: $("#txtSubject").val(),
description: $("#addEventDesc").val(),
start: $("#txtStartdate").val(),
end: $("#txtEnddate").val()
};
var ChkBox = document.getElementById("rbtnHourly");
if (ChkBox.checked == true) {
**eventToAdd = {**
FREQ: "Hourly",
INTERVAL: $("#updown").val(),
BYSETPOS: "",
BYDAY: "",
BYMONTH: "",
BYMONTHDAY: ""
};
}
var ChkBox = document.getElementById("rbtnDaily");
if (ChkBox.checked == true) {
var rbtnEveryday = document.getElementById("rbtnEveryday");
if (rbtnEveryday.checked == true) {
**eventToAdd = {**
FREQ: "Daily",
INTERVAL: $("#TextBox1").val(),
BYSETPOS: "",
BYDAY: "MO,TU,WE,TH,FR,SA,SU",
BYMONTH: "",
BYMONTHDAY: ""
};
}
else {
**var eventToAdd1 = {**
FREQ: "Daily",
INTERVAL: 1,
BYSETPOS: "",
BYDAY: "MO,TU,WE,TH,FR",
BYMONTH: "",
BYMONTHDAY: ""
};
};
}

I'm not entirely sure what you are asking but take a look at jQuery.extend()
http://api.jquery.com/jQuery.extend/
This enables you to extend an object with other values

You add values to an existing object by assigning to properties to it like this:
if (ChkBox.checked) {
eventToAdd.FREQ = "Hourly";
eventToAdd.INTERVAL = $("#updown").val();
eventToAdd.BYSETPOS = "";
eventToAdd.BYDAY = "";
eventToAdd.BYMONTH = "";
eventToAdd.BYMONTHDAY = "";
}

Related

React Native - Array of objects in state not updating correctly

I really think I'm going crazy here. So I made a shopping-type app, add to cart and etc.
I have extra comments on each Item which the user can enter any text they want to. The state is correct on "onChangeText" of the input, I checked it with the console. However, when I want to save it (after an edit of the cart), despite the console.log's making sense and that showing the correct state etc, the options changes successfully, but the comments does not. This is very weird as all the other cart array object do change, except the comment. Here is the code:
saveItemCart() {
var index = this.state.cartItems.indexOf(x => x.date === this.state.dateAdded);
let cartItemsArray = this.state.cartItems;
temp = { 'catNumber': this.state.catNumber, 'itemNumber': this.state.itemNumber, 'quantity': this.state.itemQuantity, 'options': this.state.selectedOptions, 'date': this.state.dateAdded, 'comments': this.state.commentsText};
cartItemsArray[index] = temp;
this.setState({ cartItems: cartItemsArray }, () => {
this.updateTotal();
this.setState({ selectedOptions: [], checked: [] })
})
}
State:
state = {
ModalItemShown: false,
ModalCartShown: false,
ModalEditShown: false,
isShowToast: false,
isShowToastError: false,
rest_id: this.props.route.params['restaurantid'],
menuData: this.getMenu(),
catNumber: 1,
itemNumber: 1,
dateAdded: null,
commentsText: "",
cartItems: [],
checked: [],
selectedOptions: [],
total: 0,
itemQuantity: 1,
}
Input (inside the render):
<View style={styles.modalOptions}>
<Input placeholder="..." placeholderTextColor="gray" defaultValue={this.state.commentsText} onChangeText={text => this.setState({ commentsText: text }, () => {console.log(this.state.commentsText)})} />
</View>
<Button shadowless style={styles.button1} color="warning" onPress={() => {
let my = this;
this.showToast(true);
setTimeout(function () { my.showToast(false) }, 1000);
this.saveItemCart();
this.hideModalEdit(false);
}}
>Save</Button>
The problem is in the input of the EDIT cart modal(i.e. page). If the user puts the comment initially before adding it to his cart, then when he opens the edit modal it has the correct comment. If I change it in the edit and click save, and check again, it does not work.
updateTotal:
updateTotal() {
var cartArrayLen = this.state.cartItems.length;
var i;
var j;
var total = 0;
var cart = this.state.cartItems;
for (i = 0; i < cartArrayLen; i++) {
var catNum = cart[i]["catNumber"];
var itemNum = cart[i]["itemNumber"];
var q = cart[i]["quantity"];
var itemPrice = this.state.menuData[catNum - 1][catNum.toString()]["itemsarray"][itemNum]["price"];
itemPrice = Number(itemPrice.replace(/[^0-9.-]+/g, ""));
total = total + (itemPrice * q);
var allItemOptions = this.state.menuData[catNum - 1][catNum.toString()]["itemsarray"][itemNum].options;
var k;
for (k = 0; k < cart[i].options.length; k++) {
var title = cart[i].options[k]["title"];
var index_onmenu = allItemOptions.findIndex(x => x.title === title);
var option_price;
if (Array.isArray(cart[i].options[k].indexes)) {
for (j = 0; j < cart[i].options[k].indexes.length; j++) {
var price_index = cart[i].options[k].indexes[j];
option_price = allItemOptions[index_onmenu].price[price_index]
total = total + Number(option_price) * q
}
} else {
j = cart[i].options[k].indexes
option_price = allItemOptions[index_onmenu].price[j]
total = total + Number(option_price) * q
}
}
};
console.log("New Total: " + total);
this.setState({ total: total }, () => {
this.setState({ itemQuantity: 1 })
})
}
I don't see where you defined the temp variable, but assuming that it is defined somewhere, I think the problem is in how you are updating the cartItems array. Let me explain it by adding some comments in your code:
saveItemCart() {
var index = this.state.cartItems.indexOf(x => x.date === this.state.dateAdded);
let cartItemsArray = this.state.cartItems; // --> Here you are just copying the array reference from the state
temp = { 'catNumber': this.state.catNumber, 'itemNumber': this.state.itemNumber, 'quantity': this.state.itemQuantity, 'options': this.state.selectedOptions, 'date': this.state.dateAdded, 'comments': this.state.commentsText};
cartItemsArray[index] = temp;
this.setState({ cartItems: cartItemsArray }, () => { // --> then you just updated the content of the array keeping the same reference
this.updateTotal();
this.setState({ selectedOptions: [], checked: [] })
})
}
Try doing creating a new array, so the react shallow comparison algorithm can track the state change, like this:
this.setState({ cartItems: Array.from(cartItemsArray) }, /* your callback */);
or
this.setState({ cartItems: [...cartItemsArray]}, /* your callback */);
Hope it helps!

Robot allowed the website but being identified and rejected

I need to do web scraping for a website which has allowed robot access. Below is the robot.txt file's content.
User-agent: *
Disallow:
Sitemap:https://www.sample.com/sitemap-index.xml
But when I try to fetch the website's content using nokogiri, it's being detected.
Nokogiri::HTML(open('https://www.sample.com/search?q=test', :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))
Here the output:
> (Document:0x3fda40e7cf70 {
name = "document",
children = [
#(DTD:0x3fda40e9591c { name = "html" }),
#(Element:0x3fda40e8c95c {
name = "html",
attributes = [ #(Attr:0x3fda4071a598 { name = "style", value = "height:100%" })],
children = [
#(Element:0x3fda3fefa28c {
name = "head",
children = [
#(Element:0x3fda401a3088 {
name = "meta",
attributes = [ #(Attr:0x3fda40ebd7a0 { name = "name", value = "ROBOTS" }), #(Attr:0x3fda40ebd778 { name = "content", value = "NOINDEX, NOFOLLOW" })]
}),
#(Element:0x3fda4074faf4 {
name = "meta",
attributes = [ #(Attr:0x3fda3ff0beec { name = "name", value = "format-detection" }), #(Attr:0x3fda3ff0bed8 { name = "content", value = "telephone=no" })]
}),
#(Element:0x3fda401ca700 {
name = "meta",
attributes = [ #(Attr:0x3fda401c2050 { name = "name", value = "viewport" }), #(Attr:0x3fda401c217c { name = "content", value = "initial-scale=1.0" })]
}),
#(Element:0x3fda4079a284 {
name = "meta",
attributes = [ #(Attr:0x3fda4078bfb8 { name = "http-equiv", value = "X-UA-Compatible" }), #(Attr:0x3fda4078bf04 { name = "content", value = "IE=edge,chrome=1" })]
})]
}),
#(Element:0x3fda407e2e6c {
name = "body",
attributes = [ #(Attr:0x3fda430205f0 { name = "style", value = "margin:0px;height:100%" })],
children = [
#(Element:0x3fda4072e2a0 {
name = "iframe",
attributes = [
#(Attr:0x3fda3ff45214 {
name = "src",
value = "/_Incapsula_Resource?SWUDNSAI=28&xinfo=5-66719320-0%200NNN%20RT%281543054979096%20247%29%20q%280%20-1%20-1%20-1%29%20r%280%20-1%29%20B12%284%2c315%2c0%29%20U2&incident_id=245000650118470008-256430953704260629&edet=12&cinfo=04000000"
}),
#(Attr:0x3fda3ff451d8 { name = "frameborder", value = "0" }),
#(Attr:0x3fda3ff451b0 { name = "width", value = "100%" }),
#(Attr:0x3fda3ff45188 { name = "height", value = "100%" }),
#(Attr:0x3fda3ff45174 { name = "marginheight", value = "0px" }),
#(Attr:0x3fda3ff4514c { name = "marginwidth", value = "0px" })],
children = [ #(Text "Request unsuccessful. Incapsula incident ID: 245000650118470008-256430953704260629")]
})]
})]
})]
})
How can I achieve this web scraping?

Kendo UI Treelist rows disappears after editing

I use Kendo UI in ASP .NET MVC app. I have Kendo Treelist. Sometimes, after editing a row, all rows disappear, and I see only root element without child rows. Is it Kendo bug?Or I can prevent it? And when rows have disappeared, I refresh page, do the same changes and save treelist - the treelist works correctly.
var parsedXmlDataInJson = #Html.Raw(#ViewBag.XmlData); //jsonarray data
$( document ).ready(function() {
});
function ShowMessage(message,timeout) //пока сообщению пользователю в левом верхнем углу
{
var divMessage = $('#toggler');
if(divMessage.css('display') != 'none')
{
divMessage.clearQueue();
divMessage.stop();
divMessage.css('display','none');
}
if (timeout == 0)
divMessage.text(message).toggle('slow');
else
divMessage.text(message).toggle('slow').delay(timeout).toggle('slow');
}
var treelistds = new kendo.data.TreeListDataSource({ //CRUD for dataSource
transport: {
read: function(e) {
e.success(parsedXmlDataInJson);
},
update: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
value = updatedItem;
return false;
}
});
e.success();
},
create: function(e) {//Works for root element when editing only once - it's broke my treelist.
e.data.Id = GetId();
parsedXmlDataInJson.push(e.data);
e.success(e.data);
},
destroy: function(e) {
var updatedItem = e.data;
$.each(parsedXmlDataInJson, function(indx, value) {
if (value.id == updatedItem.Id) {
parsedXmlDataInJson.splice(indx, 1);
}
});
e.success();
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
batch: false,
schema: {
model: {
id: "Id",
parentId: "parentId",
fields: {
Id: {
type: "number",
editable: true,
nullable: false
},
parentId: {
field: "parentId",
nullable: true
}
}
}
}
});
$("#treeList").kendoTreeList({
resizable: true,
dataSource: treelistds,
toolbar: ["create"],
columns: [{
field: "typeAndAttributes",
width:400
}, {
field: "text",
title: "Текст",
}, {
field: "cData",
title: "CDATA",
}, { //my custom command
command: ["edit", "destroy", "createchild", {
name: "commentOut",
text: "commentOut",
click: function(e) {
var dataItem = this.dataItem($(e.target).closest("tr")); ///my custom command
dataItem.commentedOut = !dataItem.commentedOut;
var isCommentedOut = dataItem.commentedOut;
var childNotes = this.dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) //
{
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
//обновляем цвет и текст кнопок у всех элементов вызывая dataBound
$("#treeList").data("kendoTreeList").refresh();
},
}, ]
}],
messages: {
commands: {
edit: "Изменить",
destroy: "Удалить",
createchild: "Добавить"
}
},
dataBound: function(e) {
this.autoFitColumn(3);
Databound(e.sender, e.sender.table.find("tr"));
},
editable: true,
editable: {
mode: "popup",
template: kendo.template($("#popup-editor").html()),
window: {
width:800
}
},
edit: function(e) { //invokes when popup open
$("#date").kendoDateTimePicker({
});
$("#cDataEditor").kendoEditor({
tools: [
"formatting", "bold", "italic", "underline", "insertUnorderedList",
"insertOrderedList", "indent", "outdent", "createLink", "unlink"
],
resizable: {
content: true,
toolbar: true,
max:350
}
});
//my custom logic. Popup contains many fileds splitted from one model field
if (!e.model.isNew()) { //split typeAndAttrubites to popup's fileds
var fileds = e.model.typeAndAttributes.split(';').
filter(function(v) {
return v !== ''
});
e.container.find("#type").val(fileds[0]);
var length = fileds.length;
for (i = 1; i < length; i++) {
var keyAndValue = fileds[i].split('=');
if (keyAndValue[0] != "id")
e.container.find("#" + keyAndValue[0].trim()).val(keyAndValue[1].trim());
else
e.container.find("#xmlId").val(keyAndValue[1].trim());
}
}
},
save: function(e) { //invokes when saving
var splitter = "; ";
var inputValue = $("input[id='type']").val().trim();
if (e.model.type !== undefined) {
e.model.typeAndAttributes = e.model.type;
} else {
e.model.typeAndAttributes = inputValue;
}
var allInputs = $(":input[data-appointment=attributes]");
allInputs.each(function(index, input) { //collect inputs in one filed
var attrName;
var attrValue;
if (input.id != "id") {
attrName = input.id;
e.model[attrName];
} else {
attrName = "id";
attrValue = e.model["xmlId"];
}
//значение изменили и оно не пустое
if (attrValue !== undefined && attrValue !== "") {
if (attrValue == false)
return true;
e.model.typeAndAttributes += splitter + attrName + "=" + attrValue;
}
//my custom logic
else if (input.value.trim() && input.value != "on") {
e.model.typeAndAttributes += splitter + attrName + "=" + input.value.trim();
}
})
}
});
//рекурсивно помечаем ряды как закомментированные или нет
function SetChildrenIsCommentedOut(dataItem, isCommentedOut) {
var childNotes = $("#treeList").data("kendoTreeList").dataSource.childNodes(dataItem);
childNotes.forEach(function(childModel, i) {
childModel.commentedOut = isCommentedOut;
SetChildrenIsCommentedOut(childModel, isCommentedOut);
})
}
//Раскрашивает строки соответственно значению закомментировано или нет
function Databound(sender, rows) {
rows.each(function(idx, row) {
var dataItem = sender.dataItem(row);
if (dataItem.commentedOut) {
//обозначаем ряд как закомментированный
$(row).css("background", "#DCFFE0");
$(row).find("[data-command='commentout']").html("Раскомментировать");
} else {
//обозначаем ряд как незакомментированный
$(row).css("background", "");
$(row).find("[data-command='commentout']").html("Закомментировать");
}
})
}
});
var currentId = 0;
function GetId() { //генерирование Id для новых записей
var dataSource = $("#treeList").data("kendoTreeList").dataSource;
do {
currentId++;
var dataItem = dataSource.get(currentId);
} while (dataItem !== undefined)
return currentId;
}

Error in ODataMetadata.js SAP Hana Cloud

In the app that I am creating I have a home view when the createCaseButton is clicked the createCase view is opened, but when I click to open this view I am getting the following error please see attached image. I can't seem to figure out why it is doing this. Any help would be amazing
Errors in console
Here is my code:
CreateCase controller:
jQuery.sap.require("sap.ui.commons.MessageBox");
sap.ui.controller("casemanagement.CreateCase", {
onInit: function() {
var sOrigin = window.location.protocol + "//" + window.location.hostname
+ (window.location.port ? ":" + window.location.port : "");
var caseTrackerOdataServiceUrl = sOrigin + "/CaseTracker/#/case.svc";
var odataModel = new sap.ui.model.odata.ODataModel(caseTrackerOdataServiceUrl);
odataModel.setCountSupported(false);
this.getView().setModel(odataModel);
},
AddCase : function(aCaseType,aReason,aDateOpened,aEmployee,aDescription,aComment,aAttachment){
if(aCaseType != "" && aReason != "" && aDateOpened != "" && aEmployee != "" && aDescription != "" && aComment != "")
{
var Cases = {};
Cases.caseTypeId = aCaseType;
Cases.reasonId = aReason;
Cases.dateOpened = aDateOpened;
Cases.employeeId = aEmployee;
Cases.description = aDescription;
Cases.comments = aComment;
Cases.stageId = "open"
this.getView().getModel().create("/CreateCase", Cases, null, this.successMsg, this.errorMsg);
Cases = {};
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("CreateCasePage");
}
else
{
sap.ui.commons.MessageBox.alert("Please fill in all fields before submitting")
}
},
successMsg : function() {
sap.ui.commons.MessageBox.alert("Case has been successfully created");
},
errorMsg : function() {
sap.ui.commons.MessageBox.alert("Error occured when creating the case");
},
CreateCase View:
sap.ui.jsview("casemanagement.CreateCase", {
/** Specifies the Controller belonging to this View.
* In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
* #memberOf casemanagement.CreateCase.CreateCase
*/
getControllerName : function() {
return "casemanagement.CreateCase";
},
/** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.
* Since the Controller is given to this method, its event handlers can be attached right away.
* #memberOf casemanagement.CreateCase.CreateCase
*/
createContent : function(oController) {
var aPanel = new sap.ui.commons.Panel({width:"810px"});
aPanel.setTitle(new sap.ui.core.Title({text:"Create New Case"}));
var aMatrix = new sap.ui.commons.layout.MatrixLayout({layoutFixed:true, width:"610px",columns:8});
aMatrix.setWidths("110px","100px","100px","300px");
var bMatrix = new sap.ui.commons.layout.MatrixLayout({layoutFixed:true,width:"610px", columns:2});
aMatrix.setWidths("110px","500px");
//first row of fields
var caseTypeLabel = new sap.ui.commons.Label({text:"Case Type"});
var caseTypeInput = new sap.ui.commons.TextField({width:"100%", id:"caseTypeId", value:''});
caseTypeLabel.setLabelFor(caseTypeInput);
aMatrix.createRow(caseTypeLabel,caseTypeInput);
//second row
var reasonLabel = new sap.ui.commons.Label({text:"Reason"});
var reasonInput = new sap.ui.commons.TextField({width:"100%", id:"reasonId", value:''});
reasonLabel.setLabelFor(reasonInput);
aMatrix.createRow(reasonLabel,reasonInput);
//third row
var dateOpenedLabel = new sap.ui.commons.Label({text:"Date Opened"});
var dateOpenedInput = new sap.ui.commons.TextField({widht:"100%", id: "dateOpenedId", value:''});
dateOpenedLabel.setLabelFor(dateOpenedInput);
aMatrix.createRow(dateOpenedLabel,dateOpenedInput)
//fourth row
var employeeLabel = new sap.ui.commons.Label({text:"Employee"});
var employeeIDInput = new sap.ui.commons.TextField({width:"100%", id:"employeeId",value:''});
var employeeNameInput = new sap.ui.commons.TextField({width:"100%"});
aMatrix.createRow(employeeLabel,employeeIDInput,employeeNameInput);
//fifth row
var descriptionLabel = new sap.ui.commons.Label({text:"Description"});
var descriptionInput = new sap.ui.commons.TextField({width:"100%",id:"descriptionId",value:''});
descriptionLabel.setLabelFor(descriptionInput);
aMatrix.createRow(descriptionLabel,descriptionInput)
aPanel.addContent(aMatrix);
var bPanel = new sap.ui.commons.Panel({width:"810px"});
bPanel.setTitle(new sap.ui.core.Title({text:"Actions"}));
bPanel.setCollapsed(false);
var cMatrix = new sap.ui.commons.layout.MatrixLayout({layoutFixed:true,width:"810px",columns:2});
cMatrix.setWidths("110px","700px");
var attachmentLabel = new sap.ui.commons.Label({text:"Attachments"});
var addAttachmentButton = new sap.ui.commons.FileUploader({
uploadUrl : "../../../../../upload",
name: "attachmentUploader",
uploadOnChange: true
});
var commentsLabel = new sap.ui.commons.Label({text:"Comments"});
var commentsInput = new sap.ui.commons.TextField({width:"95%",id:"commentsId",value:''});
var submitButton = new sap.ui.commons.Button({id:"createCaseButtonId",text:"Submit", press : function(){oController.AddCase(
sap.ui.getCore().getControl("caseTypeId").getValue(),
sap.ui.getCore().getControl("reasonId").getValue(),
sap.ui.getCore().getControl("dateOpenedId").getValue(),
sap.ui.getCore().getControl("employeeId").getValue(),
sap.ui.getCore().getControl("descriptionId").getValue(),
sap.ui.getCore().getControl("commentsId").getValue()
)}
});
cMatrix.createRow(attachmentLabel,addAttachmentButton);
cMatrix.createRow(commentsLabel,commentsInput);
cMatrix.createRow(submitButton);
bPanel.addContent(cMatrix);
var container = new sap.ui.layout.VerticalLayout({
content: [aPanel,bPanel]
});
return container;
},
});
Home controller:
sap.ui.controller("casemanagement.Home", {
/**
* Called when a controller is instantiated and its View controls (if
* available) are already created. Can be used to modify the View before it
* is displayed, to bind event handlers and do other one-time
* initialization.
*
* #memberOf casemanagement.Home.Home
*/
// onInit : function() {
//
// },
loadCreateCase : function() {
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("CreateCasePage");
},
loadSearchCase : function() {
this.router = sap.ui.core.UIComponent.getRouterFor(this);
this.router.navTo("SearchCasePage");
}
Home view:
sap.ui.jsview("casemanagement.Home", {
/** Specifies the Controller belonging to this View.
* In the case that it is not implemented, or that "null" is returned, this View does not have a Controller.
* #memberOf casemanagement.Home.Home
*/
getControllerName : function() {
return "casemanagement.Home";
},
/** Is initially called once after the Controller has been instantiated. It is the place where the UI is constructed.
* Since the Controller is given to this method, its event handlers can be attached right away.
* #memberOf casemanagement.Home.Home
*/
createContent : function(oController) {
var oPanelButtons = new sap.ui.commons.Panel({width:"600px",position:"center"});
oPanelButtons.setTitle(new sap.ui.core.Title({text:"Case Management"}));
var oMatrix = new sap.ui.commons.layout.MatrixLayout({layoutFixed: true, width:"400px",columns:4, position:"center"});
oMatrix.setWidths("100px","100px","100px","100px");
var createCaseButton = new sap.ui.commons.Button({id:'createId',text:"Create Case",press : function(){oController.loadCreateCase()}});
var searchButton = new sap.ui.commons.Button({text:"Search Cases",press : function(){oController.loadSearchCase()}});
var analyticsButton = new sap.ui.commons.Button({id:'analyticsId',text:"Case Analytics"});
var helpButton = new sap.ui.commons.Button({id:'helpId',text:"Help"});
oMatrix.createRow(createCaseButton,searchButton,analyticsButton,helpButton);
oPanelButtons.addContent(oMatrix);
var oPanelTable = new sap.ui.commons.Panel({width:"600px",position:"center"});
var oTable = new sap.m.Table({
inset: true,
headerText: "Open Cases Pending Your Action",
headerDesign : sap.m.ListHeaderDesign.Standard,
mode: sap.m.ListMode.None,
includeItemInSelection: true
});
oTable.addColumn(new sap.m.Column({
inset : true,
header: new sap.ui.commons.Label({text: "Case#"}),
}));
oTable.addColumn(new sap.m.Column({
inset : true,
header: new sap.ui.commons.Label({text: "Submitted By"}),
}));
oTable.addColumn(new sap.m.Column({
inset : true,
header: new sap.ui.commons.Label({text: "Created On"}),
}));
oTable.addColumn(new sap.m.Column({
inset : true,
header: new sap.ui.commons.Label({text: "Case Type"}),
}));
oPanelTable.addContent(oTable);
var container = new sap.ui.layout.VerticalLayout({
id: "container",
content:[oPanelButtons,oPanelTable]
});
return container;
},
});

OncellChange Event of Slickgrid

I have a slickgrid with a checkbox column.
I want to capture the row id when the checkbox in the selected row is checked or unchecked.
Attached is the script for slickgrid in my view
I want when user checks the checkbox, active column in database should be set to true and when it is unchecked, Active column should be set to false.
<script type="text/javascript">
//$('input[type="button"]').enabled(false);
var grid;
var columnFilters = {};
var jsonmodel = #Html.Raw(Json.Encode(Model));
//function LoadNewMessagesData(messages) {
var dataView;
var data = [];
////console.log('lena:' + subdata.length);
$.each(jsonmodel, function (idx, spotlight) {
var pd = moment(spotlight.PostedDate);
data.push({ id: spotlight.ID, Department: spotlight.SubSection,Title: spotlight.Title, PostedDate: pd.format('YYYY-MM-DD'), Active: spotlight.Active })
});
var columns = [
{ id: '0', name: "Department", field: "Department", sortable: true},
{ id: '1', name: "Title", field: "Title", sortable: true},
{ id: '2', name: "PostedDate", field: "PostedDate", sortable: true }
];
var checkboxSelector = new Slick.CheckboxSelectColumn({
cssClass: "slick-cell-checkboxsel"
})
columns.push(checkboxSelector.getColumnDefinition());
var options = {
enableCellNavigation: true,
explicitInitialization: true,
enableColumnReorder: false,
multiColumnSort: true,
autoHeight: true,
forceFitColumns: true
};
dataView = new Slick.Data.DataView();
grid = new Slick.Grid("#myGrid", dataView, columns, options);
grid.setSelectionModel(new Slick.RowSelectionModel());
var pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));
grid.registerPlugin(checkboxSelector);
dataView.onRowCountChanged.subscribe(function (e, args) {
grid.updateRowCount();
grid.render();
});
dataView.onRowsChanged.subscribe(function (e, args) {
grid.invalidateRows(args.rows);
console.log('testing');
grid.render();
});
dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
var options = grid.getOptions();
if (options.enableAddRow != enableAddRow) {
grid.setOptions({ enableAddRow: enableAddRow });
}
});
var rowIndex;
grid.onCellChange.subscribe(function (e, args) {
console.log('onCellChange');
rowIndex = args.row;
});
if (grid.getActiveCell()) {
}
//onSelectedRowsChanged event, if row number was changed call some function.
grid.onSelectedRowsChanged.subscribe(function (e, args) {
if (grid.getSelectedRows([0])[0] !== rowIndex) {
console.log('onSelectedRowsChanged');
}
});
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
var comparer = function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
}
dataView.sort(comparer, args.sortAsc);
});
grid.init();
dataView.beginUpdate();
dataView.setItems(data);
// dataView.setFilter(filter);
dataView.endUpdate();
//}
function RefreshMessagesGrid() {
//console.log('RefreshMessagesGrid');
//grid.invalidate();
grid.invalidateRows();
// Call render to render them again
grid.render();
grid.resizeCanvas();
}
</script>`enter code here`
Thanks in Advance !!!
You have to bind click event on rows....and get the id of the row whose checkbox is checked/unchecked
function bindClickOnRow() {
if($(this).find('.checkboxClass').attr('checked') == 'checked'){
checked = true;
} else {
checked = false;
}
rowId = $(this).attr('id');
}

Resources