Getting the Control inside a table - javascript

I'm trying to get the control which is inside of a cell table; in my table I have different controls, labels, checkboxes, etc.
I basically need to get the control which is used in that table
var x = document.getElementById('myTable').rows[0].cells;
alert(x[0].innerText);
//alert(x[3].innerHTML);
if (x.Control == checkbox) {
x.checked = true;
}
This will be in a loop but for now I just need to be able to check the checkbox by grabbing the control and setting that control to true
Any hints/help would be great

I doesn't really understand what you exactly need is it
document.getElementById("checkbox").checked = true;
here checkbox is the id of a particular checkbox

I would put a unique id on the form element instead and use that to grab it. In this way you can change the structure in the future. Example: perhaps you no longer want to use a table grid, but a grid of divs.
When you use innerHTML you will might also grab textnodes and other things you put in the cell.
An alternative - if you really want to find a specific cell in a table - is to give each cell a unique id on the form "cell-4-5" where 4 is the row and 5 is the column.
[EDIT]
If you want to have the cell contents returned as a DOM-object then childNodes can be used:
var x = document.getElementById('myTable').childNodes[0].childNodes[0].childNodes
If you want to have the cell contents returned as a string then innerHTML can be used:
var x = document.getElementById('myTable').childNodes[0].childNodes[0].innerHTML
To check if the checkbox is checked you need to keep it as a DOM element and thus use the first version.

Related

How to get any column of any row of a Table in HTML?

Suppose there is Table with variable number of rows of fixed number of columns, and suppose each row has a button too, now I want to select for example a column's value(let's say this selected column is textarea, so I select it's content) when that row's button is clicked.
For example in above image I want that if submit is pressed than all data of 'textarea' of corresponding row should be stored in a variable.
You can use the jQuery closest() function to find an element near the clicked button. Add click handlers to the buttons and then traverse up to find the textarea.
$('.button').on("click",function(){
var thisRowsTA = $(this).closest("textarea");
console.log($(thisRowsTA).val());
});
A simply way is to:
Put an ID pattern to your textareas, like: txt_area_1, txt_area_2, txt_area_3.
Then, on the Click Event of your buttons, make them catch the corresponding textarea in their row. Use the ID patterns to do this.
Post your code for further help.
You will need to ad an event handler for each button. Inside of that you can write something like this.
function eventHandler(e){
var row = this; // start at the button
while(row.nodeName != 'TR' && row.parent){
// go up till we find the row
row = row.parent;
}
var textArea = row.querySelector('textarea');
var value = textArea.value;
// do something with supplied feedback.
}
In order to attach the handlers, you would do something like this.
function attachTableEvents(){
var table = document.querySelector('table'); // or more specific selector if needed
var buttons = table.querySelectorAll('button');
for (var i = buttons.length; i--;){
buttons[i].addEventListener(eventHandler);
}
}
Counting on the DOM structure is really BAD.
I would put an attribute in my controls that holds the line number. Then when clicking an element you can easily query the DOM by element type and the property value to get any elements in this line.
Later if you change to DIVs or change structure your will still run correctly

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

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.

Determine row and column index of input in table

I'm working on creating a javascript based spreadsheet application. Right now I can dynamically create the spreadsheet as a table with a supplied number of rows and columns and a text input in each cell as can be seen in this picture.
I'd like to have a generic event tied to all of the inputs in the table in which I am able to determine the row index and column index of the input that fired the event. Something like this:
$('.spreadsheet-cell').click(function () {
var rowIndex = $(this).attr('rowIndex');
var columnIndex = $(this).attr('columnIndex');
});
I originally tried implementing things by dynamically adding row and column index attributes to the html input element when I create it but when I add rows or columns after the original spreadsheet has been created things get messy trying to shift the value of these attributes around. I think I could make that method work if it came down to it but it seems messy and I'd prefer not to mess around so much with the DOM when I figure that there is probably some way using jQuery to determine the relative index of the parent <td> and <tr>.
Use jQuery .index. Within your function:
var rowIndex = $("#table tr").index($(this).closest('tr'));
var colIndex = $("#table td").index(this);

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