For Loop is giving stop script error in IE - javascript
(function ($) {
// ***********************************************
//The main fixedTable function
$.fn.fixedTable = function (opts) {
//default options defined in $.fn.fixedTable.defaults - at the bottom of this file.
var options = $.extend({}, $.fn.fixedTable.defaults, opts);
var mainid = "#" + options.outerId;
var tbl = this;
var layout = buildLayout(tbl, opts);
//see the buildLayout() function below
var fixedArea = $(".fixedArea").width() - 150;
//alert($.fn.fixedTable.defaults);
//we need to set the width (in pixels) for each of the tables in the fixedContainer area
//but, we need to subtract the width of the fixedColumn area.
var w = options.width - options.fixedColumnWidth;
//sanity check
if (w <= 0) { w = options.width; }
//alert(options.width);
$(".fixedContainer", layout).width(w);
$(".fixedContainer ." + options.classHeader, layout).css({
//width: (w) + "px",
width: "100%",
"float": "left",
"overflow": "hidden"
});
$(".fixedContainer .fixedTable", layout).css({
"float": "left",
//width: (w + 8) + "px",
width: "100%",
"overflow": "auto"
});
$(".fixedContainer", layout).css({
//width: w - 1,
//width: "68%",
"float": "left"
});
//adjust the main container to be just larger than the fixedTable
$(".fixedContainer ." + options.classFooter, layout).css({
width: (w) + "px",
"float": "left",
"overflow": "hidden"
});
$("." + options.classColumn + " > .fixedTable", layout).css({
"width": options.fixedColumnWidth,
"overflow": "hidden",
"border-collapse": $(tbl).css("border-collapse"),
"padding": "0"
});
$("." + options.classColumn, layout).width(options.fixedColumnWidth);
$("." + options.classColumn, layout).height(options.height);
$("." + options.classColumn + " ." + options.classHeader + " table tbody tr td", layout).width(options.fixedColumnWidth);
$("." + options.classColumn + " ." + options.classFooter + " table tbody tr td", layout).width(options.fixedColumnWidth);
//adjust the table widths in the fixedContainer area
var fh = $(".fixedContainer > ." + options.classHeader + " > table", layout);
var ft = $(".fixedContainer > .fixedTable > table", layout);
var ff = $(".fixedContainer > ." + options.classFooter + " > table", layout);
var maxWidth = fh.width();
if (ft.length > 0 && ft.width() > maxWidth) { maxWidth = ft.width(); }
if (ff.length > 0 && ff.width() > maxWidth) { maxWidth = ff.width(); }
if (fh.length) { fh.width(maxWidth); }
if (ft.length) { ft.width(maxWidth); }
if (ff.length) { ff.width(maxWidth); }
//adjust the widths of the fixedColumn header/footer to match the fixed columns themselves
$("." + options.classColumn + " > ." + options.classHeader + " > table > tbody > tr:first > td", layout).each(function (pos) {
var tblCell = $("." + options.classColumn + " > .fixedTable > table > tbody > tr:first > td:eq(" + pos + ")", layout);
var tblFoot = $("." + options.classColumn + " > ." + options.classFooter + " > table > tbody > tr:first > td:eq(" + pos + ")", layout);
var maxWidth = $(this).width();
if (tblCell.width() > maxWidth) { maxWidth = tblCell.width(); }
if (tblFoot.length && tblFoot.width() > maxWidth) { maxWidth = tblFoot.width(); }
$(this).width(maxWidth);
$(tblCell).width(maxWidth);
if (tblFoot.length) { $(tblFoot).width(maxWidth); }
});
//set the height of the table area, minus the heights of the header/footer.
// note: we need to do this after the other adjustments, otherwise these changes would be overwrote
var h = options.height - parseInt($(".fixedContainer > ." + options.classHeader, layout).height()) - parseInt($(".fixedContainer > ." + options.classFooter, layout).height());
var diff = $(".fixedArea").width() - options.fixedColumnWidth - w;
var diffadd = $(".fixedContainer").width() + diff;
$(".fixedContainer", layout).css("width", diffadd);
// Fix Hight:Left and right Header table
var leftTable = $(".fixedColumn .fixedHead table").height();
var rightTable = $("#fixeddiv .fixedHead table").height();
$(".fixedColumn .fixedHead table").height(rightTable);
$("#fixeddiv .fixedHead table").height(rightTable);
//sanity check
if (h < 0) { h = options.height; }
$(".fixedContainer > .fixedTable", layout).height(h);
$("." + options.classColumn + " > .fixedTable", layout).height(h);
//Adjust the fixed column area if we have a horizontal scrollbar on the main table
// - specifically, make sure our fixedTable area matches the main table area minus the scrollbar height,
// and the fixed column footer area lines up with the main footer area (shift down by the scrollbar height)
var tblWidth = $("#Open_Text_General").width();
if (diffadd >= tblWidth) {
var h = $(".fixedContainer > .fixedTable", layout)[0].offsetHeight;
} else {
var h = $(".fixedContainer > .fixedTable", layout)[0].offsetHeight - 17;
}
$("." + options.classColumn + " > .fixedTable", layout).height(h); //make sure the row area of the fixed column matches the height of the main table, with the scrollbar
// Apply the scroll handlers
//$(".fixedContainer > .fixedTable", layout).scroll(function () {
//handleScroll(mainid, options);
//});
//the handleScroll() method is defined near the bottom of this file.
//$.fn.fixedTable.adjustSizes(mainid);
adjustSizes(options);
return tbl;
}
//function to support scrolling of title and first column
fnScroll = function () {
$('#divHeader').scrollLeft($('#table_div').scrollLeft());
$('#firstcol').scrollTop($('#table_div').scrollTop());
}
function buildLayout(src, options) {
//create a working area and add it just after our table.
//The table will be moved into this working area
var area = $("<div class=\"fixedArea\" style=\"float: left;width:100%;\"></div>").appendTo($(src).parent());
//fixed column items
var fc = $("<div class=\"" + options.classColumn + "\" style=\"float: left;\"></div>").appendTo(area);
var fch = $("<div class=\"" + options.classHeader + "\"></div>").appendTo(fc);
var fct = $("<div class=\"fixedTable\" id=\"firstcol\"></div>").appendTo(fc);
var fcf = $("<div class=\"" + options.classFooter + "\"></div>").appendTo(fc);
//fixed container items
var fcn = $("<div class=\"fixedContainer\" id=\"fixeddiv\"></div>").appendTo(area);
var fcnh = $("<div class=\"" + options.classHeader + "\" id=\"divHeader\"></div>").appendTo(fcn);
var fcnt = $("<div class=\"fixedTable\" id=\"table_div\" style=\"position: relative; overflow: scroll\" onscroll=\"fnScroll()\"></div>").appendTo(fcn);
var fcnf = $("<div class=\"" + options.classFooter + "\"></div>").appendTo(fcn);
//create the fixed column area
if (options.fixedColumns > 0 && !isNaN(options.fixedColumns)) {
buildFixedColumns(src, "thead", options.fixedColumns, fch);
buildFixedColumns(src, "tbody", options.fixedColumns, fct);
buildFixedColumns(src, "tfoot", options.fixedColumns, fcf);
//see the buildFixedColumns() function below
}
//Build header / footer areas
buildFixedTable(src, "thead", fcnh);
buildFixedTable(src, "tfoot", fcnf);
//see the buildFixedTable() function below
//Build the main table
//we'll cheat here - the src table should only be a tbody section, with the remaining columns,
//so we'll just add it to the fixedContainer table area.
fcnt.append(src);
return area;
}
/* ******************************************************************** */
// duplicate a table section (thead, tfoot, tbody), but only for the desired number of columns
function buildFixedColumns(src, section, cols, target) {
//TFOOT - get the needed columns from the table footer
if ($(section, src).length) {
var colHead = $("<table width=\"100%\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\" class=\"leftcol\"></table>").appendTo(target);
//If we have a thead or tfoot, we're looking for "TH" elements, otherwise we're looking for "TD" elements
var cellType = "td"; //deafault cell type
if (section.toLowerCase() == "thead" || section.toLowerCase() == "tfoot") { cellType = "th"; }
//check each of the rows in the thead
$(section + " tr", src).each(function () {
var tr = $("<tr></tr>").appendTo(colHead);
$(cellType + ":lt(" + cols + ")", this).each(function () {
$("<td>" + $(this).html() + "</td>").addClass(this.className).attr("id", this.id).appendTo(tr);
//Note, we copy the class names and ID from the original table cells in case there is any processing on them.
//However, if the class does anything with regards to the cell size or position, it could mess up the layout.
//Remove the item from our src table.
$(this).remove();
});
});
}
}
/* ******************************************************************** */
// duplicate a table section (thead, tfoot, tbody)
function buildFixedTable(src, section, target) {
if ($(section, src).length) {
var th = $("<table width=\"100%\" id=\"addcols\" cellpadding=\"3\" cellspacing=\"0\" border=\"0\" align=\"left\" class=\"\"></table>").appendTo(target);
var tr = null;
//If we have a thead or tfoot, we're looking for "TH" elements, otherwise we're looking for "TD" elements
var cellType = "td"; //deafault cell type
if (section.toLowerCase() == "thead" || section.toLowerCase() == "tfoot") { cellType = "th"; }
$(section + " tr", src).each(function () {
var tr = $("<tr></tr>").appendTo(th);
$(cellType, this).each(function () {
$("<td class=\'header\'>" + $(this).html() + "</td>").appendTo(tr);
});
});
//The header *should* be added to our head area now, so we can remove the table header
$(section, src).remove();
}
}
// ***********************************************
// Handle the scroll events
function handleScroll(mainid, options) {
//Find the scrolling offsets
var tblarea = $(mainid + " .fixedContainer > .fixedTable");
var x = tblarea[0].scrollLeft;
var y = tblarea[0].scrollTop;
$(mainid + " ." + options.classColumn + " > .fixedTable")[0].scrollTop = y;
$(mainid + " .fixedContainer > ." + options.classHeader)[0].scrollLeft = x;
$(mainid + " .fixedContainer > ." + options.classFooter)[0].scrollLeft = x;
}
// ***********************************************
// Reset the heights of the rows in our fixedColumn area
function adjustSizes(options) {
var Id = options.outerId;
var maintbheight = options.height;
var backcolor = options.Contentbackcolor;
var hovercolor = options.Contenthovercolor;
var fixedColumnbackcolor = options.fixedColumnbackcolor;
var fixedColumnhovercolor = options.fixedColumnhovercolor;
// row height
$("#" + Id + " ." + options.classColumn + " .fixedTable table tbody tr").each(function (i) {
var maxh = 0;
var fixedh = $(this).height();
var contenth = $("#" + Id + " .fixedContainer .fixedTable table tbody tr").eq(i).height();
if (contenth > fixedh) {
maxh = contenth;
}
else {
maxh = fixedh;
}
//$(this).height(contenth);
$(this).children("td").height(maxh);
$("#" + Id + " .fixedContainer .fixedTable table tbody tr").eq(i).children("td").height(maxh);
});
//adjust the cell widths so the header/footer and table cells line up
var ccount = $("#" + Id + " .fixedContainer ." + options.classHeader + " table tr:first td").size();
var widthArray = new Array();
var totall = 0;
$("#" + Id + " .fixedContainer ." + options.classHeader + " table tr:first td").each(function (pos) {
var cwidth = $(this).width();
$("#" + Id + " .fixedContainer .fixedTable table tbody td").each(function (i) {
if (i % ccount == pos) {
if ($(this).width() > cwidth) {
cwidth = $(this).width();
}
}
});
widthArray[pos] = cwidth;
totall += (cwidth + 2);
});
var contentH = $("#" + Id + " .fixedContainer .fixedTable table").height();
var addwidth = widthArray.length;
var ww = addwidth * 3 + addwidth;
if (contentH > 610) {
if ($.browser.msie && $.browser.version.substr(0, 1) > 7) {
var newwidth = $("#fixeddiv").width() - (17 + ww);
} else {
var newwidth = $("#fixeddiv").width() - 17;
}
} else {
var newwidth = $("#fixeddiv").width();
}
//More column added
$("#" + Id + " .fixedContainer ." + options.classHeader + " table").width(newwidth);
$("#" + Id + " .fixedContainer .fixedTable table").width(newwidth);
var widthTdArray = new Array();
for (i = 0; i < widthArray.length; i++) {
var headtdWd = $(this).width();
$("#" + Id + " .fixedContainer ." + options.classHeader + " table tr td").each(function (j) {
if (j % ccount == i) { headtdWd = $(this).width(); }
}); // Get Header Section width value
widthTdArray[i] = headtdWd;
}
for (i = 0; i < widthArray.length; i++) {
$("#" + Id + " .fixedContainer ." + options.classHeader + " table tr:last td").each(function (j) {
if (j % ccount == i) { // Fix width for Header section
$(this).css("width", widthTdArray[i] + "px");
$(this).css("min-width", widthTdArray[i] + "px");
$("#addcols table tr:last td span").css("width", widthTdArray[i] + "px");
if ($.browser.msie && $.browser.version.substr(0, 1) > 7) {
$("#fixeddiv table tr td span").css("width", (widthTdArray[i] - 3) + "px");
} else {
$("#fixeddiv table tr td span").css("min-width", widthTdArray[i] + "px");
}
//if ($.browser.msie && $.browser.version.substr(0,1) > 7 || $.browser.mozilla){
// $("#addcols table tr:last td span").css("min-width", widthTdArray[i] + "px");
//}
}
});
$("#" + Id + " .fixedContainer .fixedTable table tr:nth-child(3) td").each(function (j) {
if (j % ccount == i) { // Fix width for Content section
$(this).css("width", widthTdArray[i] + "px");
$(this).css("min-width", widthTdArray[i] + "px");
$("#fixeddiv table tr td span").css("width", widthTdArray[i] + "px");
if ($.browser.msie && $.browser.version.substr(0, 1) > 7) {
$("#fixeddiv table tr td span").css("width", (widthTdArray[i] - 3) + "px");
} else {
$("#fixeddiv table tr td span").css("min-width", widthTdArray[i] + "px");
}
//if ($.browser.msie && $.browser.version.substr(0,1) > 7 || $.browser.mozilla){
// $("#fixeddiv table tr td span").css("min-width", widthTdArray[i] + "px");
//}
}
});
}
if (contentH > 610) {
$("#fixeddiv .fixedHead table tr:first td:last").css("padding-left", 19);
$("#fixeddiv .fixedHead table tr:last td:last").css("padding-left", 19);
}
// mouse in/out fixedColumn's fixedtable, change background color.
$("#" + Id + " ." + options.classColumn + " .fixedTable table tr").each(function (i) {
$(this).mouseover(function () {
$(this).children("td").css({
"background-color": fixedColumnhovercolor
});
var obj = $("#" + Id + " .fixedContainer .fixedTable table tr").eq(i);
obj.children("td").css({
"background-color": hovercolor
});
obj.children("td").children("pre").css({
"background-color": hovercolor
});
});
$(this).mouseout(function () {
$(this).children("td").css({
"background-color": fixedColumnbackcolor
});
var obj = $("#" + Id + " .fixedContainer .fixedTable table tr").eq(i);
obj.children("td").css({
"background-color": backcolor
});
obj.children("td").children("pre").css({
"background-color": backcolor
});
});
});
// mouse in/out fixedContainer's fixedtable, change background color.
$("#" + Id + " .fixedContainer .fixedTable table tr").each(function (i) {
$(this).mouseover(function () {
$(this).children("td").css({
"background-color": hovercolor
});
$(this).children("td").children("pre").css({
"background-color": hovercolor
});
var obj = $("#" + Id + " ." + options.classColumn + " .fixedTable table tr").eq(i);
obj.children("td").css({
"background-color": fixedColumnhovercolor
});
});
$(this).mouseout(function () {
$(this).children("td").css({
"background-color": backcolor
});
$(this).children("td").children("pre").css({
"background-color": backcolor
});
var obj = $("#" + Id + " ." + options.classColumn + " .fixedTable table tr").eq(i);
obj.children("td").css({
"background-color": fixedColumnbackcolor
});
});
});
var contenttbH = $("#" + Id + " .fixedContainer .fixedTable table").height();
if (contenttbH < maintbheight) {
$("#" + Id + " ." + options.classColumn + " .fixedTable").height(contenttbH + 20);
$("#" + Id + " .fixedContainer .fixedTable").height(contenttbH + 20);
$("#" + Id + " .fixedContainer ." + options.classHeader).width($("#" + Id + " .fixedContainer ." + options.classHeader).width());
$("#" + Id + " .fixedContainer ." + options.classFooter).width($("#" + Id + " .fixedContainer ." + options.classHeader).width());
}
else {
//offset the footer by the height of the scrollbar so that it lines up right.
$("#" + Id + " ." + options.classColumn + " > ." + options.classFooter).css({
"position": "relative",
"top": 16
});
}
// Set .header class css style
var header_bgcolor = $(".header").css("background-color");
var color_head = $(".header").css("color");
$(".fixedHead td").css("background-color", header_bgcolor);
$(".fixedHead td").css("color", color_head);
$(".fixedHead a").css("color", color_head);
}
window.onunload = null;
})(jQuery);
While executing above script i am getting error "stop this script" in IE 6 & IE 7, Line no 287 for loop is creating this error i think, please suggest me changes so i can fix this
*Can any one help me out to fix this please ?*
"stop this script" doesn't have to be the result of an error inside your script, it simply says that your script is currently freezing the browser, because it takes to long to execute the instructions inside.
So you have to optimize the script. If you want us to help you to optimize the script you should provide the markup of the document or a demo, and a short description of the desired operations of the script.
Related
How to Add Export button in Jquery Custom Datatable
I am using a Web Template for my web site. I am developing with ASP.NET webform. The data will be shown in a Gridview. The Template also has a custom datatable file but without an Export button. I am sharing the js file here. Can anyone help me to edit the jquery and add the export button (PDF, Excel, and Copy)! Thanks (function($) { 'use strict'; $.HSCore.components.HSDatatables = { /** * * * #var Object _baseConfig */ _baseConfig: { paging: true }, /** * * * #var jQuery pageCollection */ pageCollection: $(), /** * Initialization of Datatables wrapper. * * #param String selector (optional) * #param Object config (optional) * * #return jQuery pageCollection - collection of initialized items. */ init: function(selector, config) { this.collection = selector && $(selector).length ? $(selector) : $(); if (!$(selector).length) return; this.config = config && $.isPlainObject(config) ? $.extend({}, this._baseConfig, config) : this._baseConfig; this.config.itemSelector = selector; this.initDatatables(); return this.pageCollection; }, initDatatables: function() { //Variables var $self = this, config = $self.config, collection = $self.pageCollection; //Actions this.collection.each(function(i, el) { //Variables var $this = $(el), $info = $this.data('dt-info'), $search = $this.data('dt-search'), $entries = $this.data('dt-entries'), $pagination = $this.data('dt-pagination'), $detailsInvoker = $this.data('dt-details-invoker'), pageLength = $this.data('dt-page-length'), isResponsive = Boolean($this.data('dt-is-responsive')), isSelectable = Boolean($this.data('dt-is-selectable')), isColumnsSearch = Boolean($this.data('dt-is-columns-search')), isColumnsSearchTheadAfter = Boolean($this.data('dt-is-columns-search-thead-after')), isShowPaging = Boolean($this.data('dt-is-show-paging')), scrollHeight = $this.data('dt-scroll-height'), paginationClasses = $this.data('dt-pagination-classes'), paginationItemsClasses = $this.data('dt-pagination-items-classes'), paginationLinksClasses = $this.data('dt-pagination-links-classes'), paginationNextClasses = $this.data('dt-pagination-next-classes'), paginationNextLinkClasses = $this.data('dt-pagination-next-link-classes'), paginationNextLinkMarkup = $this.data('dt-pagination-next-link-markup'), paginationPrevClasses = $this.data('dt-pagination-prev-classes'), paginationPrevLinkClasses = $this.data('dt-pagination-prev-link-classes'), paginationPrevLinkMarkup = $this.data('dt-pagination-prev-link-markup'), table = $this.DataTable({ pageLength: pageLength, responsive: isResponsive, scrollY: scrollHeight ? scrollHeight : '', scrollCollapse: scrollHeight ? true : false, paging: isShowPaging ? isShowPaging : config.paging, drawCallback: function( settings ) { var api = this.api(), info = api.page.info(); $($info).html( 'Showing ' + (info.start + 1) + ' to ' + info.end + ' of ' + info.recordsTotal + ' Entries' ); } }), info = table.page.info(), paginationMarkup = ''; if (scrollHeight) { $(table.context[0].nScrollBody).mCustomScrollbar({ scrollbarPosition: 'outside' }); } $($search).on('keyup', function() { table.search(this.value).draw(); }); if(isColumnsSearch == true) { table.columns().every(function () { var that = this; if(isColumnsSearchTheadAfter == true) { $('.dataTables_scrollFoot').insertAfter('.dataTables_scrollHead'); } $('input', this.footer()).on('keyup change', function () { if (that.search() !== this.value) { that .search(this.value) .draw(); } }); $('select', this.footer()).on('change', function () { if (that.search() !== this.value) { that .search(this.value) .draw(); } }); }); } $($entries).on('change', function() { var val = $(this).val(); table.page.len(val).draw(); // Pagination if (isShowPaging == true) { $self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, val); } }); if(isSelectable == true) { $($this).on('change', 'input', function() { $(this).parents('tr').toggleClass('checked'); }) } // Pagination if (isShowPaging == true) { $self.pagination($pagination, table, paginationClasses, paginationItemsClasses, paginationLinksClasses, paginationNextClasses, paginationNextLinkClasses, paginationNextLinkMarkup, paginationPrevClasses, paginationPrevLinkClasses, paginationPrevLinkMarkup, info.pages); } // Details $self.details($this, $detailsInvoker, table); //Actions collection = collection.add($this); }); }, pagination: function(target, table, pagiclasses, pagiitemclasses, pagilinksclasses, paginextclasses, paginextlinkclasses, paginextlinkmarkup, pagiprevclasses, pagiprevlinkclasses, pagiprevlinkmarkup, pages) { var info = table.page.info(), paginationMarkup = ''; for (var i = 0; i < info.recordsTotal; i++) { if (i % info.length == 0) { paginationMarkup += i / info.length == 0 ? '<li class="' + pagiitemclasses + '"><a id="datatablePaginationPage' + (i / info.length) + '" class="' + pagilinksclasses + ' active" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>' : '<li class="' + pagiitemclasses + '"><a id="' + target + (i / info.length) + '" class="' + pagilinksclasses + '" href="#!" data-dt-page-to="' + (i / info.length) + '">' + ((i / info.length) + 1) + '</a></li>'; } } $('#' + target).html( '<ul class="' + pagiclasses + '">\ <li class="' + pagiprevclasses + '">\ <a id="' + target + 'Prev" class="' + pagiprevlinkclasses + '" href="#!" aria-label="Previous">' + pagiprevlinkmarkup + '</a>\ </li>' + paginationMarkup + '<li class="' + paginextclasses + '">\ <a id="' + target + 'Next" class="' + paginextlinkclasses + '" href="#!" aria-label="Next">' + paginextlinkmarkup + '</a>\ </li>\ </ul>' ); $('#' + target + ' [data-dt-page-to]').on('click', function() { var $page = $(this).data('dt-page-to'), info = table.page.info(); $('#' + target + ' [data-dt-page-to]').removeClass('active'); $(this).addClass('active'); table.page($page).draw('page'); }); $('#' + target + 'Next').on('click', function() { var $currentPage = $('#' + target + ' [data-dt-page-to].active'); table.page('next').draw('page'); if ($currentPage.parent().next().find('[data-dt-page-to]').length) { $('#' + target + ' [data-dt-page-to]').removeClass('active'); $currentPage.parent().next().find('[data-dt-page-to]').addClass('active'); } else { return false; } }); $('#' + target + 'Prev').on('click', function() { var $currentPage = $('#' + target + ' [data-dt-page-to].active'); table.page('previous').draw('page'); if ($currentPage.parent().prev().find('[data-dt-page-to]').length) { $('#' + target + ' [data-dt-page-to]').removeClass('active'); $currentPage.parent().prev().find('[data-dt-page-to]').addClass('active'); } else { return false; } }); }, format: function(value) { return value; }, details: function(el, invoker, table) { if (!invoker) return; //Variables var $self = this; $(el).on('click', invoker, function() { var tr = $(this).closest('tr'), row = table.row(tr); if (row.child.isShown()) { row.child.hide(); tr.removeClass('opened'); } else { row.child($self.format(tr.data('details'))).show(); tr.addClass('opened'); } }); } }; })(jQuery);
Hiding elements with JS
UPDATE: I changed my script to this and it works. Way simpler and it works. function myFunction(valor) { var elementos = document.getElementsByClassName("inner"); var i; for (i = 1; i < elementos.length+1; i++) { document.getElementById("age"+i).style.visibility = "hidden"; } document.getElementById("age"+valor).style.visibility = "visible"; } I have this script: function myFunction(valor) { alert("Has seleccionado " + valor); var elementos = document.getElementsByClassName("inner"); //alert ("Tienes " + elementos.length + " elementos."); var i; for (i = 1; i < elementos.length + 1; i++) { var sty = document.getElementById("age" + i); //alert("age"+i); if (getComputedStyle(sty).getPropertyValue("visibility") == "hidden") { document.getElementById("age" + valor).style.visibility = "visible"; } else { document.getElementById("age" + i).style.visibility = "hidden"; } } } That I control with a slider control. What I'm doing is hiding or showing some divs with depending of what I choose from the slider. This is how I paint my data before trying to hide or shsow elements with the slider: $(window).load(function() { $.getJSON('http://xxxxx/xxxxx.json', function(data) { var output = "<ul class='lista'><div class='outer'>"; for (var i in data.lbclassic) { output += "<div style='visibility:hidden;' class='inner'id=" + "age" + data.lbclassic[i].ageinweeks + ">" + "<p>" + data.lbclassic[i].ageinweeks + "--" + data.lbclassic[i].cumul + "--" + data.lbclassic[i].perhh + "--" + data.lbclassic[i].perhd + "--" + data.lbclassic[i].eggweightinweek + "--" + data.lbclassic[i].eggmasscumul1 + "--" + data.lbclassic[i].eggmassinweek + "--" + data.lbclassic[i].eggmasscumul + "</p></div>"; } output += "</div></ul>"; document.getElementById("placeholder").innerHTML = output; }); }); This works great until one point - once I get to the last element (90 in this case), it won't show up.
Isn't it more easy to use the css "display:none;" feature for hidding your element. .yourclass{ display:none; } just edit the class with js Link to CSS
function myFunction(valor) { var elementos = document.getElementsByClassName("inner"); var i; for (i = 1; i < elementos.length+1; i++) { document.getElementById("age"+i).style.visibility = "hidden"; } document.getElementById("age"+valor).style.visibility = "visible"; }
Unable to change the button value next to another button - Javascript - JQuery
Is it possible to once press a random value on from the 25 given and change the value of the button next to it? http://jsfiddle.net/ehcfqm22/ $(document).on('click', '#table input',function () { var value1 = ""; value1 = $(this).val(); }); I'm able to get the current button value but that's about it.
You can change the value of the next button e.g. adding $(this).parent("td").next("td").find("input").val(value1); to your function. I've added it in your Fiddle For the previous button, it's $(this).parent("td").prev("td").find("input").val(value1); $(document).on('click', '#table input', function () { var value1 = ""; value1 = $(this).val(); $(this).parent("td").next("td").find("input").val(value1); }); for (a = 1; a <= 25; a++) { var makeTable = false if (!makeTable) { $('#table').append('<table>'); } $('#table').append('<tr>'); for (i = 1; i <= 5; i++) { $('#table').append('<td>' + '<input type="button" class="numVa" value="' + a + '">' + '</td>'); a++; } a--; $('#table').append('</tr>'); } $('#table').append('</table>'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="table"></div> Update: For the previous unclear requirement that not only the value of the next and/or previous button should be changed, but also the values of the buttons above and below, adjusted Fiddle Adjustment as follows: For getting the index/number of the cell and row of the clicked button, using index(): var bCell = $(this).parent("td"); var bRow = bCell.parent("tr"); var bCellNr = bCell.parent("tr").children().index(bCell); var bRowNr = $("#table tr").index(bRow); And then setting the values for the buttons with the same index in the following (bRowNr + 1) and previous (bRowNr - 1) rows : $("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " ), #table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )") .find("input").val(value1); in case the button in the bottom row should change the value in case a button in the first row is clicked or $("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " )") .find("input").val(value1); if(bRowNr > 0) { $("#table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )") .find("input").val(value1); } in case clicking a button in the first row shouldn't change last row button values (Fiddle. for this version). As the previous table contained wrong markup (empty rows, several empty tables), the cleaned up code with the second variety as snippet: $(document).on('click', '#table input', function () { var value1 = ""; value1 = $(this).val(); $(this).parent("td").prev("td").find("input").val(value1); $(this).parent("td").next("td").find("input").val(value1); var bCell = $(this).parent("td"); var bRow = bCell.parent("tr"); var bCellNr = bCell.parent("tr").children().index(bCell); var bRowNr = $("#table tr").index(bRow); $("#table tr:eq(" + (bRowNr + 1) + ") td:eq(" + bCellNr + " )").find("input").val(value1); if (bRowNr > 0) { $("#table tr:eq(" + (bRowNr - 1) + ") td:eq(" + bCellNr + " )").find("input").val(value1); } }); for (a = 1; a <= 25; a++) { $tr = $("<tr>"); for (i = 1; i <= 5; i++) { $tr.append('<td>' + '<input type="button" class="numVa" value="' + a + '">' + '</td>'); a++; } a--; $('#table').append($tr); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="table"></div>
If I understood your question correctly, pushing a button should make the text of the button next to it change, if so, this will work $(document).on('click', '#table input',function () { $(this).next("input[type='button']").val('i\'ve been changed by the '+$(this).val()); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="table"><input type="button" value="first button"/><input type="button" value="second button"/><input type="button" value="third button"/><div>
How make sticky headers for several table headers?
So I have a several tables with several rows and columns. Since the information is huge I want to keep the table headers fixed on top when scrolling. When the one header comes, the previous one will hide and the current one will stay fixed. This is the js code I have so far: function makeTableHeadersSticky(tableId) { var thArr = $(tableId + " th"); var thWidthsArr = []; var calcWidth = 0; $(tableId + " th").each(function(){ calcWidth = $(this).css("width"); thWidthsArr.push(calcWidth); }); var pos = $(tableId).offset(); var thTop = pos.top + "px"; var count = 0; $(tableId + " tr:first-child > th").each(function(){ $(this).css("width", thWidthsArr[count]); count++; }); count = 0; $(tableId + " tr:last-child > td").each(function(){ $(this).css("width", thWidthsArr[count]); count++; }); $(window).scroll(function() { //var firstRow = $(tableId + " tr:first-child").offset(); var lastRow = $(tableId + " tr:last-child").offset(); var w = $(window); //console.log("(first,last): ("+(firstRow.top-w.scrollTop())+","+(lastRow.top-w.scrollTop())+")"); if(($(window).scrollTop() > pos.top) && (lastRow.top-w.scrollTop() >= 0)) { $(tableId + " tr:first-child").css("position", "fixed"); $(tableId + " tr:first-child").css("top", "0px"); $(tableId + " tr:first-child").css("left", "9px"); } else { $(tableId + " tr:first-child").css("position", "static"); $(tableId + " tr:first-child").css("top", thTop); } }); } makeTableHeadersSticky("#myTable"); If you see on my code I played with the positions of the table and the last row of the table to see where the table is. This way I can set the header position as fixed or static. Here is my jsfiddle
Everything works just fine here. You just omitted to call the makeTableHeadersSticky function for the second table : makeTableHeadersSticky("#myTable2"); demo
Convert .each() because it's slow
I'm using the .each function to hide/show columns of a table. But the problem is that the code is very slow in IE. After searching on internet I saw that could be because of my .each() function and $(this). For more information why I'm using this code, you can look at this post: Hide/show column This is my old code: include JQuery.min.js on page javascript: $(function () { $('table th').each(function (_id, _value) { if(_id > 2){ if($(this).find("a").text()){ $('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) { $('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle(); e.preventDefault(); }); } else{ if($(this).find("div").text()){ $('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) { $('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle(); e.preventDefault(); }); } } } }); }); HTML: <div id="togglers">Show/Hide columns<br/></div> I tried to convert my javascript with this code (Source: jQuery very slow in IE), but I think there is still a problem with my i(or _id) and _value... $(function () { var items = $('table th'); var $currentItem; for (var i = 0, j = items.length; i < j; i++) { $currentItem = $(items[i]); // in place of $(this) function (i, _value) { if(i > 2){ if($currentItem.find("a").text()){ $('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) { $('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle(); e.preventDefault(); }); } else{ if($currentItem.find("div").text()){ $('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) { $('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle(); e.preventDefault(); }); } } } } } }); It's possible that I need to use other code. Any suggestion is welcome! Tnx.
Performance issue has nothing to do with .each. DOM is tens of times slower than any way to iterate collection you choose. Instead of iterating table on every toggle you can make CSS do it for you. Demo. $(function() { var togglers = $('#togglers'), //cache toggler ref addToggler = function(idx, text) { togglers.append('<span class="toggler" data-id="' + idx + '">' + text + '</span>'); }, table = $('#table'), //cache table ref columns = 0; //generate styles for 100 columns table :) (function generateStyleSheet(len){ var styles = [], i = 0; for(; i < len; i++) { styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ; } $('<style>' + styles.join('\n') + '</style>').appendTo(document.body); }(100)) //bind on click once using event delegation togglers.on('click', '.toggler', function(e){ var id = $(e.target).toggleClass('pressed').data('id'); table.toggleClass('hide-' + id); }); //generate all togglers and count em table.find('th').each(function(idx, header){ header = $(header); addToggler(idx, header.text()); //make toggler header.addClass('column-' + idx); //add class column-i columns++; }); //add column-i class to tds table.find('td').each(function(idx, td) { $(td).addClass('column-' + (idx%columns)); }); });