C# GridView Implementing clickable cells from dynamically created DataTable - javascript

I've been trying to work on this for awhile now, and I'm at my wits end. I have a web form with a GridView control. The data source is a dynamically created DataTable, and I would like to do this without Template Fields if at all possible. My goal is to have 4 checkbox columns that the user can click to change the values. I just made the 4 columns data type bool so that they automatically show up as checkboxes. I know how to select a row with a little help from javascript, but being able to detect which column was clicked has thus eluded me.
Relevant code showing how I am currently selecting the row:
function getSelectedRow(row)
{
jQuery(row).children(":first").children(":first")[0].click();
}
Code Behind:
protected void gvReviewOrder_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string onClick = "javascript: getSelectedRow(this);";
e.Row.Attributes["onclick"] = onClick;
e.Row.Style["cursor"] = "pointer";
}
}
The latest thing I have tried was using JQuery from the following thread:
Table row and column number in jQuery
Instead of using an alert, I was trying to update the clicked column index into a hidden field, so this is what my current Javascript function looks like:
$("td").click(function ()
{
var colIndex = $(this).parent().children().index($(this));
$("#hfColumnId").val(colIndex);
});
So hypothetically my hidden field "hfColumnId" should be updated when the cell is clicked, but that is not happening. Do I need to add code on my OnRowDataBound Event to add the click event first?
As you can probably guess, I'm still learning when it comes to web forms, and I'm just over my head right now. Any help would be much appreciated.
So to make a long question short, is there any way to return the column index when a cell is clicked via jquery from a GridView control?
Thanks in advance!
edit
I found this thread from last year with a solution, but they suggest setting EnableEventValidation to false, and I know this is not recommended. So if I could figure out how to implement that way without setting that to false it could be a potential solution maybe?
Get clicked cell index in gridview (not datagridview) asp.net

Possible solution is described in : http://www.codeproject.com/Tips/209416/Click-select-row-in-ASP-NET-GridView-or-HTML-Table :
Listing 1. Adding onClick attribute to the Table dynamically rendered by ASP.NET GridView
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e){
if (e.Row.RowType == DataControlRowType.DataRow){
// javascript function to call on row-click event
e.Row.Attributes.Add("onClick", "javascript:void SelectRow(this);");
}
}
and corresponding sample Javascript Function to perform some custom formatting of the dynamically rendered Table Row on click event (essentially implementing a Click event handler):
Listing 2. Javascript function to format Table Row onClick
<script type="text/javascript">
// format current row
function SelectRow(row) {
var _selectColor = "#303030";
var _normalColor = "#909090";
var _selectFontSize = "3em";
var _normalFontSize = "2em";
// get all data rows - siblings to current
var _rows = row.parentNode.childNodes;
// deselect all data rows
try {
for (i = 0; i < _rows.length; i++) {
var _firstCell = _rows[i].getElementsByTagName("td")[0];
_firstCell.style.color = _normalColor;
_firstCell.style.fontSize = _normalFontSize;
_firstCell.style.fontWeight = "normal";
}
}
catch (e) { }
// select current row (formatting applied to first cell)
var _selectedRowFirstCell = row.getElementsByTagName("td")[0];
_selectedRowFirstCell.style.color = _selectColor;
_selectedRowFirstCell.style.fontSize = _selectFontSize;
_selectedRowFirstCell.style.fontWeight = "bold";
}
</script>
Alternatively, instead of adding onClick attribute to each row of the table as per Listing 1, it's possible to implement this functionality with Javascript code snippet shown below:
Listing 3. Javascript Table Row onClick event handler
// ** table row click event **
function row_OnClick(tblId) {
try {
var rows = document.getElementById(tblId).rows;
for (i = 0; i < rows.length; i++) {
var _row = rows[i];
_row.onclick = null;
_row.onclick = function () {
return function () {selectRow(this);};
}(_row);
}
}
catch (err) { }
}
Practical implementation of the solution shown above (Listing 3) with complete Javascript code base can be found here: http://busny.net.
Client-side Javascript (or jQuery) scripting provides high responsiveness. This core solution could be further extended pertinent to the particular requirements. For example, individual CheckBoxes within the row object var can be addressed by using the following syntax:
row.cells[0].firstChild.checked
and so on.
Hope this may help.

Related

Get Parent Table name using Text present in td

I am developing an MVC app in which I have created two tables in view dynamically. In each table first column contains ID and last column contains save button. On click of save button I'm passing this ID to my function. Now I want to check the button was clicked from which table so that I can perform operations. I have tried many solutions but did not work. Can anybody help?
function SaveDocument(_param) {
//alert(_param + "Add");
return;
var tableRow = $("td").filter(function () {
return $(this).text() == String(_param);
}).parent('tr');
tableRow.parent().attr('uid');
}
and I have also tried links like this but none of these work.
Edit : -
I have created fiddle for this here
You mentioned that you're creating tables dynamically, so I'm assuming your click event won't fire unless you delegate it.
Try adding a class say .save to the buttons and run the below code.
$(document).on('click', '.save', function(){
console.log($(this).closest('table'));
});

count checkboxes in a form using javascript

I have quite a lot of check boxes on one form. The check boxes are in different sections of the form. I would like to count the number of checkboxes at the end of each section on my form.
For example I have 6 sections within my form and I have between 6 and 10 checkboxes within each section. I would like to have a textbox with a number value at the end of each section telling me how many check boxes were check within that particular section.
Does anyone have a script for that? I have a snippet from support staff but they don't have a full solution and I don't know JavaScript well enough to finish it. I'm through trying to figure it out so i can finish it. Here is the snippet they sent me:
<script type="text/JavaScript">
function countcheck(checkName){
inputElems = document.getElementsByName(checkName);
count = 0;
for (i = 0; i < inputElems.length; i++) {
if (inputElems.checked === true) {
count++;
document.getElementById("teval_engage7").value = count;
}
}
}
</script>
The script will only count checked checkboxes within that group only. Basically you will need a function for each of your checkbox so that you can have separated counters. This will also require an attribute to your checkbox according to the function in question:
onclick="countcheck(this.name);"
var cb_counts = {};
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
if (input.type = 'checkbox' && input.checked) {
if (cb_counts[input.name]) {
cb_counts[input.name]++;
} else {
(cb_counts[input.name] = 1);
}
}
}
Now the object cb_counts contains properties with the name of each group of checkboxes, and the values are the counts. Do with this what you wish.
Thanks for the quick reply. I use a application call rsform which helps to make forms. On the script I have "teval_engage7" is the text box which stores the value of the number of checkboxes that have been checked. "onclick="countcheck(this.name);"" is the trigger I place under each checkbox question. So when I go to the form and click on a checkbox with that trigger attached to it, the value of "1" shows up in the teval_engage7 text box. The next check box I click on then shows "2" in the teval_engage7 text box. My question is, can you te me using this script you wrote where the values are stored so I can substitute that name for my textbox name. Also, do I use my same trigger "onclick="countcheck(this.name);"" to attach to my checkbox attibute area to trigger the count?
Thanks

How to update ZK Grid values from jQuery

I have three Tabs and in each tab, I have a Grid.
The data for each Grid is coming from a database, so I am using rowRenderer to populate the Grids. The following code is common for all three Grids:
<grid id="myGrid1" width="950px" sizedByContent="true" rowRenderer="com.example.renderer.MyRowRenderer">
The rows are constructed from Doublebox objects. The data is populated successfully.
The Problem:
I need to handle multiple-cell editing on the client side. The editing is done via mouse-clicking on a particular cell and entering a value.
As example let's say that the user edits first cell on the first row and the value should be
propagated to all other cells on the same row and in all three Grids (so also the two Grids which the user currently does not see, because they are in tabpanes).
I am using jQuery to do this value propagation and it works OK.
I am passing the jQuery as follows:
doublebox.setWidgetListener(Events.ON_CHANGING, jQuerySelectors);
doublebox.setWidgetListener(Events.ON_CHANGE, jQuerySelectors);
This makes it possible to change the value in 1 cell and the change is instantly (visually) seen in all other cells filtered by jQuery selectors.
The problem is that the value is visually distributed to all the cells, but when I try to save the Grid data back to the database, the background values are the old ones.
I am assuming that ZK-Grid component is not aware that jQuery changed all the cell values. Nevertheless if I manually click on a cell that already has the NEW value (enter/leave/change focus) when I save the grid the NEW value is correct in that particular cell. Maybe that's a hint how can I resolve this.
Code of how I extract the Grid values:
Grid tGrid = (Grid) event.getTarget().getFellow("myGrid1");
ListModel model = tGrid.getModel();
MyCustomRow tRow = (MyCustomRow)model.getElementAt(i);
The model for my Grid is a List of MyCustomRow:
myGrid1.setModel(new ListModelList(List<MyCustomRow> populatedList));
I have a couple of assumptions, but whatever I have tried, hasn't worked. I have in mind that jQuery events and ZK-Events are different and probably isolated in different contexts. (Although I have tried to fire events from jQuery and so on..)
Do you have any suggestions? As a whole is my approach correct or there's another way to do this? Thanks for your time in advance!
Your problem is exactly what you are expecting.
Zk has it's own event system and do not care about your jq,
cos it's jq and zk don't observ the DOM.
The ways to solve your problem.
Use the "ZK-Way":
Simply listen at server-side and chage things there.
I am not sure if not selected Tabs
are updateable, but I am sure you could update the Grid
components on the select event of the Tab.
Fire an zk-event your self:
All you need to know, is written in the zk doc.
Basically, you collect your data at client side, send
an Event to the server via zAu.send() extract the
data from the json object at serverside and update your Grids
I would prefer the first one, cos it's less work and there should not be
a notable difference in traffic.
I post the solution we came up with:
This is the javascript attached to each Doublebox in the Z-Grid
//getting the value of the clicked cell
var currVal = jq(this).val();
//getting the next cell (on the right of the clicked cell)
objCells = jq(this).parents('td').next().find('.z-doublebox');
// if there's a next cell (returned array has length) - set the value and
// fire ZK onChange Event
if (objCells.length) {
zk.Widget.$(jq(objCells).attr('id')).setValue(currVal);
zk.Widget.$(jq(objCells).attr('id')).fireOnChange();
} else { //otherwise we assume this is the last cell of the current tab
//So we get the current row, because we want to edit the cells in the same row in the next tabs
var currRow = jq(this).parents('tr').prevAll().length;
//finding the next cell, on the same row in the hidden tab and applying the same logic
objCellsHiddenTabs = jq(this).parents('.z-tabpanel').next().find('.z-row:eq(' + currRow + ')').find('.z-doublebox');
if (objCellsHiddenTabs.length) {
zk.Widget.$(jq(objCellsHiddenTabs).attr('id')).setValue(currVal);
zk.Widget.$(jq(objCellsHiddenTabs).attr('id')).fireOnChange();
}
}
The java code in the RowRenderer class looks something like this:
...
if (someBean != null) {
binder.bindBean("tBean", someBean);
Doublebox box = new Doublebox();
setDefaultStyle(box);
row.appendChild(box);
binder.addBinding(box, "value", "tBean.someSetter");
...
private void setDefaultStyle(Doublebox box) {
box.setFormat("#.00");
box.setConstraint("no negative,no empty");
box.setWidth("50px");
String customJS = ""; //the JS above
//this is used to visually see that you're editing multiple cells at once
String customJSNoFireOnChange = "jq(this).parents('td').nextAll().find('.z-doublebox').val(jq(this).val());";
box.setWidgetListener(Events.ON_CHANGING, customJSNoFireOnChange);
box.setWidgetListener(Events.ON_CHANGE, customJS);
}
What is interesting to notice is that ZK optimizes this fireOnChange Events and send only 1 ajax request to the server containing the updates to the necessary cells.

getting data from a yui datatable

I have the following jsfiddle that generates a YUI Datatable with checkboxes, but i have a problem getting the data of ids from the table after i click the Get Records button.
anyway to call the table from the javascript?
P.S : I am using YUI2 library as my project is using that
Using Checkbox Listeners
I hope this codes show what you need http://yuilibrary.com/yui/docs/datatable/datatable-chkboxselect.html
Edit:
I update your code for adding checkboxClickEvent for handling checkbox event in each of data row and use an array to keep all of the checked record id.
var selectedID = [];
myDataTable.subscribe("checkboxClickEvent", function(oArgs){
alert("check box clicked");
var elCheckbox = oArgs.target;
var oRecord = this.getRecord(elCheckbox);
if (elCheckbox.checked) {
selectedID.push(oRecord.getData("id"));
}
else {
selectedID.pop(oRecord.getData("id"));
}
oRecord.setData("check",elCheckbox.checked);
});
Detail of working code is here.

Get child elements from a specific cell in an HTMLTableRowElement and hide/remove them?

I am working with some custom ajax functionality using Telerik's MVC Grid and I am trying to hide/remove child elements of a cell based on specific criteria, I found a similar question here: Telerik MVC Grid making a Column Red Color based on Other Column Value but couldn't get it working right.
Basically when the row is databound in the grid this event fires:
function onRowDataBound(e) {
if (e.dataItem.Status == "Submitted") {
$.each(e.row.cells, function (index, column) {
alert(column.innerHTML);
//var $header = $(column).closest('table').find('th').eq($(column).index());
//if(header text == "Actions)
//{
//Get the <a> child elements in the 'Actions' column whose class contains t-grid-Edit,
//t-grid-edit, t-grid-Delete, or t-grid-delete and set their display to none, add a css class, and remove the element entirely
//}
}
}
}
So far it's working in that I can get and iterate through each column in the row, but I am not sure what to do at this point, I found this How can I get the corresponding table header (th) from a table cell (td)? to check to make sure the column name name is Actions, but I couldn't get it working. I am not sure how to convert the javascript HTMLTableCellElement object into a jQuery object so I can use syntax I am more familiar with.
Here is what I need to do after that:
Get the child elements in the 'Actions' (has to go by column header name instead of cell index because the number of columns can change) column whose class
contains t-grid-Edit, t-grid-edit, t-grid-Delete, or t-grid-delete
Take those elements and (each of these actions would be used on different pages using similar setups):
a. Set the element's display style to none
b. Add a class to the element of name "Hidden"
c. Remove the element from the code entirely
How can I put the above functionality into my onRowDataBound function?
Thank you SO =).
I was able to figure this out with a lot of playing:
function onRowDataBound(e) {
if(e.dataItem.Status == "Submitted"){
var $row = $(e.row);
$.each($row.children("td"), function (index, column) {
var $column = $(column);
var $headerText = $column.closest('table').find('th').eq($column.index()).children(".t-link").text();
if ($headerText == "Actions") {
$.each($column.children("a.t-grid-delete, a.t-grid-Edit"), function (subIndex, link) {
$(link).remove();
});
}
});
}
}

Categories

Resources