Fixed Header for ASP NET Gridview JQuery - javascript

I've been searching a lot for ways to make my gridview header fixed I came across this JQuery code:
$(document).ready(function () {
// Code to copy the gridview header with style
var gridHeader = $('#<%=GridView1.ClientID%>').clone(true);
//Code to remove all the rows but the first row which is header row
$(gridHeader).find("tr:gt(0)").remove();
$('#<%=GridView1.ClientID%> tr th').each(function (i) {
// Here Set Width of each th from gridview to new table th
$("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
});
// Append Header to the div controlHead
$("#controlHead").append(gridHeader); // <-- HERE is WHEN IT DAMAGES OTHER JS FUNCTIONALITY
// Set its position to be fixed
$('#controlHead').css('position', 'fixed');
// Put it on top
$('#controlHead').css('top', $('#<%=GridView1.ClientID%>').offset().top);
It actually works but it makes my other JS functions to malfunction when I append this cloned header to the empty div "gridHeader"
Like this JS Function that is in charge of highlighting the selected row, it just doesn't find the Gridview anymore
// Method that will highlight row
function gridviewManipulation() {
// Get Gridview
var gridView = document.getElementById("<%= GridView1.ClientID %>");
// Loop through the Gridview
for (var i = 1; i < gridView.rows.length; i++) {
// Get the radio button of each row in the gridview and see if its checked
if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == true)
{
// Place the color for selection
gridView.rows[i].style.background = '#9bc27e';
}
else if (gridView.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == false && i % 2 == 0)
{
// If its even then place white color back
gridView.rows[i].style.background = '#FFFFFF';
}
else
{
// If its odd place the bluish back on
gridView.rows[i].style.background = '#E3EAEB';
}
}
}
Any suggestions?
Thank you!!

I believe the problem is that you are using the ID of the element to identify it.
When you run this line:
var gridHeader = $('#<%=GridView1.ClientID%>').clone(true);
You create a 2nd table element with the same ID. Subsequent calls to that ID are not working as you expect.
I'd try the following to change the id of the cloned table you create:
var gridHeader = $('#<%=GridView1.ClientID%>').clone(true).attr('id', 'newID');

Related

Event listener fails to attach or remove in some contexts

I've created a script that attaches an event listener to a collection of pictures by default. When the elements are clicked, the listener swaps out for another event that changes the image source and pushes the id of the element to an array, and that reverses if you click on the swapped image (the source changes back and the last element in the array is removed). There is a button to "clear" all of the images by setting the default source and resetting the event listener, but it doesn't fire reliably and sometimes fires with a delay, causing only the last element in a series to be collected.
TL;DR: An event fires very unreliably for no discernible reason, and I'd love to know why this is happening and how I should fix it. The JSFiddle and published version are available below.
I've uploaded the current version here, and you can trip the error by selecting multiple tables, pressing "Cancel", and selecting those buttons again. Normally the error starts on the second or third pass.
I've also got a fiddle.
The layout will be a bit wacky on desktops and laptops since it was designed for phone screens, but you'll be able to see the issue and inspect the code so that shouldn't be a problem.
Code blocks:
Unset all the selected tables:
function tableClear() {
//alert(document.getElementsByClassName('eatPlace')[tableResEnum].src);
//numResTables = document.getElementsByClassName('eatPlace').src.length;
tableArrayLength = tableArray.length - 1;
for (tableResEnum = 0; tableResEnum <= tableArrayLength; tableResEnum += 1) {
tableSrces = tableArray[tableResEnum].src;
//alert(tableSrcTapped);
if (tableSrces === tableSrcTapped) {
tableArray[tableResEnum].removeEventListener('click', tableUntap);
tableArray[tableResEnum].addEventListener('click', tableTap);
tableArray[tableResEnum].src = window.location + 'resources/tableBase.svg';
} /*else if () {
}*/
}
resTableArray.splice(0, resTableArray.length);
}
Set/Unset a particular table:
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'resources/tableBase.svg');
resTableArray.shift(this);
};
tableTap = function () {
$(this).unbind('click', tableTap);
$(this).bind('click', tableUntap);
this.setAttribute('src', 'resources/tableTapped.svg');
resTableArray.push($(this).attr('id'));
};
Convert the elements within the 'eatPlace' class to an array:
$('.eatPlace').bind('click', tableTap);
tableList = document.getElementsByClassName('eatPlace');
tableArray = Array.prototype.slice.call(tableList);
Table instantiation:
for (tableEnum = 1; tableEnum <= tableNum; tableEnum += 1) {
tableImg = document.createElement('IMG');
tableImg.setAttribute('src', 'resources/tableBase.svg');
tableImg.setAttribute('id', 'table' + tableEnum);
tableImg.setAttribute('class', 'eatPlace');
tableImg.setAttribute('width', '15%');
tableImg.setAttribute('height', '15%');
$('#tableBox').append(tableImg, tableEnum);
if (tableEnum % 4 === 0) {
$('#tableBox').append("\n");
}
if (tableEnum === tableNum) {
$('#tableBox').append("<div id='subbles' class='ajaxButton'>Next</div>");
$('#tableBox').append("<div id='cazzles' class='ajaxButton'>Cancel</div>");
}
}
First mistake is in tapping and untapping tables.
When you push a Table to your array, your pushing its ID.
resTableArray.push($(this).attr('id'));
It will add id's of elements, depending on the order of user clicking the tables.
While untapping its always removing the first table.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
resTableArray.shift(this);
So, when user clicks tables 1, 2, 3. And unclicks 3, the shift will remove table 1.
Lets fix this by removing untapped table
tableUntap = function () {
$(this).unbind('click', tableUntap);
$(this).bind('click', tableTap);
this.setAttribute('src', 'http://imgur.com/a7J8OJ5.png');
var elementID = $(this).attr('id');
var elementIndex = resTableArray.indexOf(elementID);
resTableArray.splice(elementIndex, 1);
};
So you were missing some tables after untapping.
Well lets fix tableClear,
You have a array with tapped tables, but you are searching in main array.
function tableClear() {
tableLen = resTableArray.length;
for (var i = 0; i < tableLen; i++) {
var idString = "#" + resTableArray[i];
var $element = $(idString);
$element.unbind('click', tableUntap);
$element.bind('click', tableTap);
$element.attr("src", 'http://imgur.com/a7J8OJ5.png');
}
resTableArray = [];
}
Im searching only tapped tables, and then just untap them and remove handlers.
fiddle: http://jsfiddle.net/r9ewnxzs/
Your mistake was to wrongly remove at untapping elements.

How to dynamically click a label to check entire row only?

The number of rows are dynamic so I cant fixate on the name of the row, here is the fiddle: http://jsfiddle.net/1vp29wxq/1/
$('.NameOfSensor').on("click", function () {
var tr = $(this).parents('tr:first');
var thisRow = tr.find(".rowMode");
var checkChecked = $("input[class='rowMode']:checkbox:checked");
var checkBoxes = $("input[class='rowMode']:checkbox");
if (checkChecked.length < checkBoxes.length)
{
checkBoxes.prop("checked", true);
}
else {
checkBoxes.prop("checked", false);
}
});
What I get from that is that all check boxes are selected, but I just want the ones from the row where it is clicked. Also, whatever I tried I cant seem to incorporate the 2 variables (tr and thisRow) I created, can I get some help? Also, the number of columns in which the checkboxes are, are always 6 (sometimes I just hide them).
Change your code into this:
$('.NameOfSensor').on("click", function () {
var tr = $(this).closest('tr');
var checkChecked = $(tr).find("input[class='rowMode']:checkbox:checked");
var checkBoxes = $(tr).find("input[class='rowMode']:checkbox");
if (checkChecked.length < checkBoxes.length)
{
checkBoxes.prop("checked", true);
}
else {
checkBoxes.prop("checked", false);
}
});
Your selector was wrong and got all rows.
Search for checkboxes within the clicked line:
var tr = $(this).closest('tr'); // fast alternative to `.parents('xxx:first')`
var checkChecked = $("input[class='rowMode']:checkbox:checked", tr),
checkBoxes = $("input[class='rowMode']:checkbox", tr);
DEMO: http://jsfiddle.net/1vp29wxq/2/

creating a 2 column table dynamically using jquery

I am trying to generate a table dynamically using ajax call. To simplify things i have just added my code to js fiddle here -> http://jsfiddle.net/5yLrE/81/
As you click on the button "HI" first two columns are created properly.. but some how as the td length reaches 2 . its not creating another row. The reason is that when i do find on the table elements its actually retrieving the children table elements. Can some one pls help.
I want a two column table.. Thank you.
sample code:
var tr = $("#maintable tbody tr:first");
if(!tr.length || tr.find("td:first").length >= max) {
$("#maintable").append("<tr>");
}
if(count==0) {
$("#maintable tr:last").append("<td>hi"+content+"</td>");
}
Basically the matching of descendants was allowing for great great grandchildren etc. Just needed to make the matching more specific.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5yLrE/91/
max = 2
$("button").click(function () {
var content = $('#template').html();
var $table = $("#maintable");
var tr = $table.find(">tbody>tr:last");
if (!tr.length || tr.find(">td").length >= max) {
// Append a blank row
tr = $("<tr>");
$table.append(tr);
}
tr.append("<td>hi " + content + "</td>");
});
This one always targets the last row and adds a row if it does not exists at all (or there are too many divs already) which is what I gather you intended.
I also used the templating I suggested to separate messy HTML strings from the code.
You will want to check the length of the table cells before incrementing a new table row. After you have reached your max column length, reset the row and start over.
JSFiddle
max_columns = 2;
count=0;
$("button").click(function() {
var content='column';
if(count==max_columns||!$('#maintable tr').length){
$("#maintable").append("<tr>");
count=0;
}
if(count!=max_columns)
$("#maintable tr:last").append("<td>"+content+"</td>");
else
$("#maintable tr:first").append("<td>"+content+"</td>");
count++;
});

Copying Dynamic Table Column with rows of Hidden style properties to textarea jQuery

I'm pretty new to jQuery and I'm having a little trouble accomplishing a specific function that I want for my table.
I have a db list that gets dynamically sorted and I want to be able to create a textarea that includes the text from a specific column on the click of the column header. I have some of the functionality from the code that I used from this http://jsfiddle.net/4BwGG/3/ but here are some things I just can't figure out:
I have some of the rows in my table hidden using style="display: none" property within the <tr> tag and when the script parses everything, the information from those hidden rows get included too. How do I do a check so that only the displayed rows are copied to the text area?
Here is what one row entry looks like:
<tr filtermatch="false" style="display: none;">
<td>< a href="http://example.edu">Tommy Trojan< /a>< /td>
< td>123-555-1231< /td>
< td>Statue Man< /td>
< td>[LTS1] [LTS2] [PM] [PM2] [TA1] [TA2] < /td>
< td>tommy#example.edu< /td>
< /tr>`
Here is the Function:
function SelectColumn(index, tableId) {
var columnText = 'You selected:\n\n';
var columnSelector = '#' + tableId + ' tbody > tr > td:nth-child(' + (index + 1) + ')';
var cells = $(columnSelector);
// clear existing selections
if (window.getSelection) { // all browsers, except IE before version 9
window.getSelection().removeAllRanges();
}
if (document.createRange) {
cells.each(function(i, cell) {
var rangeObj = document.createRange();
rangeObj.selectNodeContents(cell);
window.getSelection().addRange(rangeObj);
columnText = columnText + '\n' + rangeObj.toString();
});
}
else { // Internet Explorer before version 9
cells.each(function(i, cell) {
var rangeObj = document.body.createTextRange();
rangeObj.moveToElementText(cell);
rangeObj.select();
columnText = columnText + '\n' + rangeObj.toString();
});
}
alert(columnText);
}
Try wrapping the code in a conditional statement that checks the visibility of the tr.
For example:
if (document.createRange) {
cells.each(function(i, cell) {
if ($(cell).closest('tr').is(':visible')) {
var rangeObj = document.createRange();
rangeObj.selectNodeContents(cell);
window.getSelection().addRange(rangeObj);
columnText = columnText + '\n' + rangeObj.toString();
}
});
}
Of course, you'd want to do the same thing in the else block as well. But for the record, that jsFiddle did not work for me in IE7 (it throws an error about unsupported property or method).
I know you didn't ask, but unless you need the column to actually be selected, I would refactor the code. If you want the column to appear selected, I'd probably add a little CSS.
Someone else could probably improve the code even more. But here is my suggestion. I've added comments to explain what I did and why.
function SelectColumn(index, tableId) {
// cache the table selector in a local variable
// because we are going to use it more than once
var columnText = 'You selected:\n\n',
table = $('#' + tableId),
cells = table.find('td:nth-child(' + (index + 1) + ')');
// reset the background color of all cells
table.find('td').css('background-color', '#fff');
cells.each(function(i, cell) {
// turn cell into a jQuery object and cache it
// because we are going to use it more than once
cell = $(cell);
if (cell.closest('tr').is(':visible')) {
// get the cell text and trim it
// because different browsers treat newlines differently
columnText += $.trim(cell.text()) + '\n';
// set a background color on the selected cells
cell.css('background-color', '#ccc');
}
});
alert(columnText);
}
If you are using jquery it will make things very easy.
To select only visible elements you can use :visible in jquery.
$(document).ready(function(){
var textAreaContent=[];
$('tr:visible').each(function(){
var content=$('<div />').append($(this).clone()).html();
textAreaContent.push(content);
});
$('.textarea').val(textAreaContent.join(''));
});
check on jsfiddle http://jsfiddle.net/sudhanshu414/9YeLm/
Other option of selecting is using filter. This can also be useful if you want to filter on some other condition.
$(document).ready(function(){
var textAreaContent=[];
$('tr').filter(function(){ return $(this).css('display')!='none';}).each(function(){
var content=$('<div />').append($(this).clone()).html();
textAreaContent.push(content);
});
$('.textarea').val(textAreaContent.join(''));
});
Jsfiddle : http://jsfiddle.net/sudhanshu414/3GfqN/

How to tell if a row contains cells with textbox with javascript

I have a table that is built dynamically from a user specified query to a database and I want to give the user the option to edit the data from the generated HTML table. When the user double clicks on the row containing the data they want to edit, I have a new row appear underneath it with textboxes for them to submit new values. Right now, when the user clicks double clicks two rows, both rows of textboxes remain in the table and I want to delete the first row before the second shows up. My question is, what is a good was to find table rows containing textboxes so that I can perhaps use JavaScript's deleteRow() function?
I'm generating rows like so:
function editRow(row) {
var table = document.getElementById("data");
var newRow = table.insertRow(row.rowIndex + 1);
var cell;
for (var i = 0; i < row.childNodes.length; i++) {
cell = newRow.insertCell(i);
textBox = document.createElement("input");
textBox.type = "text";
textBox.placeholder = row.childNodes[i].innerHTML;
textBox.style.textAlign = "center";
textBox.style.width = "90%";
cell.appendChild(textBox);
}
}
and the only way I can I can think of doing it is something like (pseudo code):
for all table rows
if row.childNodes.innerHTML contains 'input'
deleteRow(index)
Thanks for the help
You could use jQuery. Assuming row is a DOM element, this should work:
var textBoxes = $("input:text", row);
i guess the easiest option would be to add the created rows to an array. This way you simply have to delete the rows inside the array and not iterate through the whole table.
I ended up doing the following:
function editRow(row) {
var table = document.getElementById("data");
clearExistingTextBoxes(table);
...
}
function clearExistingTextBoxes(table) {
var tBoxRow = table.getElementsByTagName("input");
if (tBoxRow.length > 0) {
tBoxRow = tBoxRow[0].parentNode.parentNode;
table.deleteRow(tBoxRow.rowIndex);
}
}
Assuming I'm only going to be clearing one row at a time.

Categories