Angular ng-grid footer is not adjusting the height according to grid - ng-grid

I want to reduce the height when a row is removed from ng-grid. I am able to delete a row reduce the grid height by a row. but grid footer is not moving from its position.
here is the code I am using
--html
<div class="gridStyle" ui-if="InterestInfo.length>0" ng-grid="gridOptions" ng- style="getTableStyle()" >
</div>
--javascript
var varFooterTempate = '<div><button type="button" class="btn btn-xs btn-success" ng-click="edit(row)" > ' +
' <span class="glyphicon glyphicon-plus"></span>' +
'</button>'
$scope.getTableStyle = function () {
var rowHeight = 35;
var headerHeight = 30;
var footerHeight = 30;
return {
height: ($scope.InterestInfo.length * rowHeight + headerHeight + footerHeight + 5) + "px"
};
};
$scope.gridOptions = {
data: 'InterestInfo',
headerRowHeight: 30,
rowHeight: 35,
footerRowHeight: 30,
showFooter: true,
footerTemplate: varFooterTempate,
columnDefs: [{ field: 'name', displayName: 'Name' },
{ field: 'type', displayName: 'Type' },
{ field: 'number', displayName: 'Number' },
{ field: '', displayName: 'Action', width: 140, sortable: false, cellTemplate: editableInPopup}],
multiSelect: false
};
$scope.removeRow = function () {
var index = this.row.rowIndex;
alert(index);
$scope.gridOptions.selectItem(index, false);
$scope.InterestInfo.splice(index, 1);
};

I believe that the documentation is currently wrong on this topic. Try setting gridFooterHeight instead of footerRowHeight in your gridOptions object.

Related

How to check jqgrid checkbox by option outside the grid

I have a jqgrid with a checkbox as a leading column. I need to be able to use an optiongroup outside of the grid to either check All or uncheck All or check Some of the rows
<input id="rblAll" type="radio" name="rblOptStatus" value="All"/>Check All
<input id="rblNone" type="radio" name="rblOptStatus" value="None"/>Uncheck All
<input id="rblSome" type="radio" name="rblOptStatus" value="Some"/>Check 60%
<input id="rblReset" type="radio" name="rblOptStatus" value="Reset" checked="checked" />Reset
So my grid is a loadOnce: true and multiselect is false. The column model is
colModel: [
{ name: 'ab', index: 'ab', width: 50, sortable: true, search: false, align: 'center', editable: true, formatter: 'checkbox', formatoptions: { disabled: false }, edittype: 'checkbox', editoptions: { value: 'True:False' } },
This is the code I was trying to use but the checkbox is not set.
$("input[name=rblOptStatus]").change(function () {
var OptStatus = $("input[name=rblOptStatus]:checked").val()
if (OptStatus == 'All') {
var rows = jQuery("#grdOptionsGrid").getDataIDs();
for (a = 0; a < rows.length; a++) {
var q = jQuery("#grdOptionsGrid").jqGrid('getCell', rows[a], 'ab'); // displays true, for a checked record.
if (q == 'False') {
//MsgBox(q);
//jQuery("#grdOptionsGrid").jqGrid('getCell', rows[a], 'ab').prop('checked', true);
$(this).prop('checked', 'True')
}
}
So how should I be looping through the grid and then checking/unchecking the rows checkbox.
I appreciate your help
You should use getGridRowById to get DOM element of row (<tr>). The method getCell gets the value (the text) and you can't use .prop('checked', true) to check the checkbox. The fixed code could be like
$("input[name=rblOptStatus]").change(function () {
var status = $("input[name=rblOptStatus]:checked").val(),
$grid = $("#grdOptionsGrid"),
ids = $grid.jqGrid("getDataIDs"),
setCheckboxes = function (maxIndex, value) {
var i, $checkbox;
for (i = 0; i < maxIndex; i++) {
$checkbox = $($grid.jqGrid('getGridRowById', ids[i]))
.children('td[aria-describedby="grdOptionsGrid_ab"]')
.find('input');
if ($checkbox.is(":checked") !== value) {
$checkbox.prop('checked', value);
}
}
};
switch (status) {
case 'All':
setCheckboxes(ids.length, true);
break;
case 'None':
setCheckboxes(ids.length, false);
break;
default: //Check 60%
setCheckboxes(ids.length, false);
setCheckboxes(ids.length*0.6, true);
}
});
See https://jsfiddle.net/OlegKi/ef6zp25g/

How to put an if condition under columns in kendo grid

Can we add a if Condition inside the column while describing the columns of the grid? Whats wrong in this code
I want to display one button in the grid under a column ,if length of the text exceeds more than 40char.
I am trying to put an if condition if the content/data is less than 40 char then display the content else display a button , On click of button open a pop-up to display the complete content inside that pop-up?
How we can put the command conditionally to display the button?
Here is my code
columns: [{
field: "id",
title: "ID",
width: "100px"
}, // fields in the grid
{
field: "name",
title: "Name",
width: "100px"
}, {
field: "remarks",
title: "Remarks",
width: "160px", // under this column button will be displayed in each
var length = 40;
if (data.remarks.length > length) { //here this condition seems to be wrong, is there any other way to display the button for this condition
command: {
name: "remarks",
text: "Remarks",
click: function (e) {
var tr = $(e.target).closest("tr");
var data = this.dataItem(tr);
var win = $('#remarksWindow');
win.html(data.remarks);
if (!win.data('kendoWindow')) {
win.kendoWindow({
width: '600px',
height: '200px',
title: 'Remarks',
actions: ['Close']
});
}
win.parent().css({
top: e.pageY - 50,
left: e.clientX - 640,
width: '600px',
height: '200px'
});
win.data('kendoWindow').open(); // open the pop-up which contains the data
return false;
}
}
}
}
},
First of all, you have a syntax error in JavaScript. Note that you can't put statements or declarations between the properties of an object:
var obj = {
a: 1,
if (true) {
b: 2;
}
}
Or
var obj = {
a: 1,
var b = 1;
}
The examples above doesn't works. So in your column property you have to use a template property:
{
field: "remarks",
title: "Remarks",
width: "160px",
template: "" // <- here goes your logic
}
So a simple template can be set as a string containing html with JavaScript logic, e.g.:
# if (remarks.length > 40) { # <input type='button' class='btn-remarks' /> # } #
Yes, you will have to set the button html by yourself. There is no way to add a condition to a command button(and that is a shame, actually).
You can check how template works here.
Then your column item should be:
{
field: "remarks",
title: "Remarks",
width: "160px",
template: "# if (remarks.length > 40) { # <input type='button' class='remarks' /> # } #"
}
Then you have to set the event for all your buttons(probably in the dataBound event):
$("#yourGrid").on("click", ".btn-remarks", function()
{
// all your click logic here
});
Give it a try and tell me what happens.
Hopefully this dojo is what you are looking for: http://dojo.telerik.com/ETora
(I have used one of Telerik's grid demos and modified to show you the principles)
The functionality you are looking for can be achieved by two means:
1) Apply a client Template to the column
2) Add a databound event that then hooks up the buttons
columns:[ {
field: "CompanyName",
title: "Company Name",
template: "#= displayTextorButton(data.CompanyName) #"
}]
function displayTextorButton(data){
var retString = '';
console.log(data);
if(data !== null && data !== undefined)
{
if(data.length > 20)
{
retString = ' <button type="button" class="btn btn-xs btn-primary"' +
'data-toggle="popover" data-placement="auto right" data-container="body" ' +
'data-content="' + kendo.htmlEncode(data) + '"' +
'data-title="Running Log Information" data-trigger="click" data-role-me="content-popover" > <span class="glyphicons glyphicons-pencil"></span> View</button>';
}
else
{
retString = '<span>' + data + '</span>';
}
}else
{
retString = '<span> - </span>';
}
return retString;
}
so the first bit I have done is added a template to the Company Name column that checks if the name is more than 20 characters if it is then it will display a button if it isn't then it will display the text as normal.
function(e){
$('button[data-role-me="content-popover"]').popover({ trigger: "focus", html: true });
}
I then hook up a databound event to the grid to then attach the event features to the "pop up" in my sample
Also note I have hooked in the bootstrap features just to make things a little easier for the demo. So this is using their popover feature. You could modify this code to work with your window.
Any issues let me know.
This is the kendo grid code
{ field: "marks", title: "marks",width: "160px",
template: function(dataItem) {
var marks = dataItem.marks;
var retString = '';
if(marks !== null && marks !== undefined)
{
if(marks.length > 40)
{
marks1 = marks.substring(0, 40)+'...';
retString1 ='<span>'+ marks1 +'</span>';
retString = retString1 + ' <button id="marksButton" type="button"' +
'data-toggle="popover" data-placement="auto right" data-container="body" ' +
'data-content="' + kendo.htmlEncode(addlRemarks) + '"' +
'data-title="marks" data-trigger="click" data-role-me="content-popover" > marks</button>';
}
else
{
retString = '<span>' + marks + '</span>';
}
}else
{
retString = '<span> - </span>';
}
return retString;
}
And its being called from a HTMl
<div class="panel-body" ng-show="accOpen[$index]">
<!-- Marks TABLE -->
<div marks-table=""
accordion-flag="accOpen[$index]"
name="name"
id="id"
>
</div>
</div>

Kendo UI Grid One column changes it effects to the another column

I have grid. In that grid, i have 3 columns like name, qty1 and qty2.
Both qty1 and qty2 will be NumericText Boxes.
here my question is if i change qty1 values this value effects to the qty2.
Example:
qty1 has a max value will be 10. based on this value qty2 will not exceed 10.
qty1 has a max value will be 20. based on this value qty2 will not exceed 20.
How i can give validation here.
You should define custom rules/messages in the kendo validator widget to check the values inputted into the second textbox against the first:
e.g.
html:
<div id="form-stuff">
<input id="Value1" name="Value1" type="number" />
<div style="clear"></div><br />
<input id="Value2" name="Value2" type="number" />
<div style="clear"></div><br />
<div class="validation-tooltip-wrapper"><span class="k-invalid-msg" data-for="Value2" style="position:relative;"></span></div>
<div style="clear"></div><br />
<button id="btn-submit" type="button" class="k-button k-button-icontext"><span class="k-icon k-update"></span>Submit</button>
<span id="results"></span>
</div>
JS:
$('#Value1').kendoNumericTextBox({
min: 0,
max: 10,
value: 0,
format: '#'
});
$('#Value2').kendoNumericTextBox({
value: 0,
min: 0,
format: '#'
});
$('#form-stuff').kendoValidator({
rules: {
qty2: function(input) {
if(input.is('[name=Value2]')) {
var input1 = $('#Value1').data('kendoNumericTextBox'), maxAmount = input1.max();
return (Number(input.val()) <= maxAmount);
}
return true;
}
},
messages: {
qty2: 'amount exceeded'
}
});
$('#btn-submit').on('click', function() {
var validator = $('#form-stuff').data('kendoValidator');
if(validator.validate()) {
$('#results').text('Valid!');
} else {
$('#results').text('Invalid!');
}
});
The jsFiddle for this can be seen here:
http://jsfiddle.net/d6R4X/7/
I hope this helps...
Finally, I solved my self. I am given the following example in JSFiddle.
html:
js:
var data = [
{ Name: "Ranga Reddy", MaxMarks: 10, MinMarks:6 },
{ Name: "Vinod Reddy", MaxMarks: 9, MinMarks:7 }
]
var dataSource = new kendo.data.DataSource({
pageSize: 20,
data: data,
autoSync: true,
schema: {
model: {
fields: {
Name: { validation: { required: true } },
MaxMarks: { type: "number", validation: { required: true, min: 0, max: 10} },
MinMarks: { type: "number", validation: { required: true} }
}
} // fields
} // model
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
height: 430,
toolbar: ["create"],
columns: [
{ field:"Name",title:"Name", width:"40%" },
{ field: "MaxMarks", title:"Max Marks", width: "20%" },
{ field: "MinMarks", title:"Min Marks", width: "20%",
editor: function (container, options) {
// create an input element
var input = $("<input name='" + options.field + "'/>");
// append it to the container
input.appendTo(container);
// initialize a Kendo UI numeric text box and set max value
input.kendoNumericTextBox({
max: options.model.MaxMarks,
min:0
});
}
},
{ command: "destroy", title: " ", width: "20%" }],
editable: true
});
see the example in jsfiddle http://jsfiddle.net/rangareddy/SJ85S/28/

asp.net-MVC Edit GridDate based on the role

I've a datagrid to show employee particular but i need to set a logic where
if Role=Manager then show all the employee and if Role=Employee show only 1 data which belong to him. Below is my code to show the employee. I managed to show all employee. Need help to set filter for employee.
View
#model IEnumerable<SealManagementPortal_3._0.Models.VOC_CUSTODIAN>
#{
ViewBag.Title = "List of Custodians";
}
<h2>Index</h2>
<p>
#if (User.IsInRole("Manager"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("#list2").jqGrid({
url: '#Url.Action("GridData", "Custodian")',
datatype: 'json',
mtype: 'GET',
colNames: ['Agent ID', 'Branch', 'Unique ID', 'Custodian Name', /*'NRIC No', 'E-Mail', 'Contact No', 'Mobile No',*/'Role', 'Details', 'Edit', 'Delete'],
colModel: [
{ name: 'Agent ID', index: '', width: 10, align: 'left' },
{ name: 'Branch', index: '', width: 10, align: 'left' },
{ name: 'Unique ID', index: '', width: 10, align: 'left' },
{ name: 'Custodian Name', index: '', width: 10, align: 'left' },
{name: 'Role', index: '', width: 10, align: 'left' },
{ name: 'Details', index: '', width: 5, align: 'left' }
, { name: 'Edit', index: '', width: 5, align: 'left' }
,{ name: 'Delete', index: '', width: 5, align: 'left' }
],
pager: jQuery('#pager2'),
rowNum: 10,
sortname: 'Id',
sortorder: "desc",
viewrecords: true,
autowidth: true,
caption: 'Custodians List'
});
});
</script>
#using (Html.BeginForm())
{
<table id="list2" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager2" class="scroll" style="text-align:center;"></div>
}
Controller
public ActionResult GridData (string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.VOC_CUSTODIAN.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from custo in db.VOC_CUSTODIAN.AsEnumerable()
select new
{
id = custo.Idx,
cell = new string []
{
custo.StaffId,
custo.Branch,
custo.UniqueId,
custo.Name,
custo.Role,
("<a href='"+ #Url.Action("Details", "Custodian") +"/"+ custo.Idx+ "'>DETAILS</a>"),
("<a href='"+ #Url.Action("Edit", "Custodian") +"/"+ custo.Idx+ "'>EDIT</a>"),
("<a href='"+ #Url.Action("Delete", "Custodian") +"/"+ custo.Idx+ "'>DELETE</a>")
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
Your view should not handle the logic, your Controller Action should. You should be able to do something like this with Roles.InUserInRole:
if (!Roles.IsUserInRole(User.Identity.Name, "Managers"))
{
jsonData.total = 1;
jsonData.page = 1;
jsonData.records = 1;
jsonData.rows = jsonData.rows.Where(x => x.id = currentUserId).ToArray()
}
return Json(jsonData, JsonRequestBehavior.AllowGet);

Custom template column does not work in JQGrid

Experts,
I have JQGrid with custom template column like Edit. the following screen display data without Edit link in last column.
Javascript code:
<script language="javascript" type="text/javascript">
function editFmatter(cellvalue, options, rowObject) {
var cellHtml = "<a href='#' originalValue='" + cellvalue + "'>" + cellvalue + "</a>";
return cellHtml;
}
function unformatEdit(cellvalue, options) {
return $(cellObject.html()).attr("originalValue");
}
jQuery(document).ready(function () {
jQuery("#list").jqGrid({
url: '#Url.Action("JQGridGetGridData", "TabMaster")',
datatype: 'json',
mtype: 'GET',
colNames: ['col ID', 'First Name', 'Last Name', 'Edit'],
colModel: [
{ name: 'colID', index: 'colID', width: 100, align: 'left', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{ name: 'FirstName', index: 'FirstName', width: 150, align: 'left', editable: true },
{ name: 'LastName', index: 'LastName', width: 150, align: 'left', editable: true },
{ name: 'Edit', index: 'Edit', width: 80, align: "center", editable: true, formatter: editFmatter, unformat: unformatEdit }
],
pager: jQuery('#pager'),
rowNum: 100,
rowList: [10, 50, 100, 150],
sortname: 'colID',
sortorder: "asc",
viewrecords: true,
multiselect: true,
imgpath: '#Url.Content("~/Scripts/themes/steel/images")',
caption: 'Tab Master Information'
}).navGrid('#pager', { edit: true, add: true, del: true },
// Edit options
{
savekey: [true, 13],
reloadAfterSubmit: true,
jqModal: false,
closeOnEscape: true,
closeAfterEdit: true,
url: '#Url.Action("JQGridEdit", "TabMaster")',
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record updated successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Add options
{
url: '#Url.Action("JQGridCreate", "TabMaster")',
closeAfterAdd: true,
afterSubmit: function (response, postdata) {
if (response.responseText == "Success") {
jQuery("#success").show();
jQuery("#success").html("Record added successfully! [" + postdata.FirstName + " " + postdata.LastName + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
// Delete options
{
url: '#Url.Action("JQGridRemove", "TabMaster")',
afterSubmit: function (response, rowid) {
if (rowid.length > 0) {
jQuery("#success").show();
jQuery("#success").html("Record deleted successfully! [" + rowid + "]");
jQuery("#success").fadeOut(6000);
return [true, response.responseText]
}
else {
return [false, response.responseText]
}
}
},
{
closeOnEscape: true,
multipleSearch: false,
closeAfterSearch: true
}
);
});
</script>
#using (Html.BeginForm())
{
<p>
#Html.ActionLink("Create New", "Create") | #Html.ActionLink("Bulk Insert", "AddList")
#* | #Html.ActionLink((string)ViewBag.RemoveSelectedTitle, "RemoveSelected")*#
</p>
<table id="list" class="scroll" cellpadding="0" cellspacing="0" width="100%">
</table>
<div id="pager" class="scroll" style="text-align: center;">
</div>
<div id="success" style="color: Green">
</div>
Controller.cs
public JsonResult JQGridGetGridData(string sidx, string sord, int rows, int page)
{
int totalRecords = Convert.ToInt32(_tabmasterService.Count());
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
IQueryable<TabMasterViewModel> tabmasters = _tabmasterService.GetQueryTabMasterList(sidx, sord, rows, page);
var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (from tm in tabmasters
select new
{
id = tm.colID,
cell = new string[] { tm.colID.ToString(), tm.FirstName, tm.LastName, "Edit" }
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
First of all I would recommend you to take a look in this and this answers which shows how you can implement Edit links in the jqGrid.
Your current code have some problems:
In the unformatEdit you forgot to define the third parameter cellObject and use undefined value.
It's not good to add attributes like originalValue which are not corresponds to HTML standards. If you do need to extend attributes you should use data- prefix in the attribute name to be HTML5 compliant. In the case you can change the code to $(cellObject).children('a:first').attr("data-originalValue"); for example.
It is not good to define global functions because of possible name conflicts. You can move declaration of the function inside of jQuery(document).ready(function () {/*here*/}); event handler. You can define the function like a variables: var editFmatter = function(cellvalue, options, rowObject) {/* the body of the function*/}; and use later in the same way like you did as before.
You should use the last version of jqGrid (currently 4.1.1). Many parameters like imgpath which you use are not exist since years (see here). If you look for more recent ASP.NET MVC code example I would recommend you take a look in the "UPDATED" part of the answer and download the corresponding code examples (the VS2008 project and the VS2010 project).
I have solved question from myself.
I have done following:
{ name: 'Edit', index: 'Edit', width: 80, align: 'center', editable: false, formatter: editFmatter, unformat: unformatEdit }
and
function editFmatter(el, cellval, opts) {
var editHTML = "<img src='Images/row_edit.gif' alt='Edit' title='Edit' onclick='openEditDialog(" + opts.rowId + ");'>";
var deleteHTML = "<img src='Images/row_delete.gif' alt='Delete' title='Delete' onclick='openDeleteDialog(" + opts.rowId + ");'>"; ;
var finalHTML = editHTML + " " + deleteHTML;
$(el).html(finalHTML);
}
function unformatEdit(cellvalue, options) {
//return $(el).html().attr("originalValue");
}
Thanks,
Imdadhusen

Resources