How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";
I am looping through a for loop to perform a simple calculation. The results of each iteration are stored into an array. The array has the correct number of elements but the output has exponentially too many elements.
HTML:
<script type="text/javascript" src="Fibonacci.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($) {
$.fn.writeText = function(content) {
var contentArray = content,
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 1000);
};
})(jQuery);
</script>
</head>
<body>
<script>
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
<h3>Fibonacci Sequence:</h3>
<p id='calculations'></p>
External JS:
var result;
var x = 0;
var y = 1;
var resultArray = [x,y];
function FibonacciCalculation(){
for(var i = 2; i < 5; i++){
result = x + y;
x = y;
y = result;
resultArray.push(result);
}
}
function getArray(){
FibonacciCalculation();
return resultArray;
}
window.onload = function(){
FibonacciCalculation();
};
You need to reset your resultArray every time you run FibonacciCalculation function:
function FibonacciCalculation() {
resultArray = [x, y]
// ...
You called getArray two times the <script> part of the html so resultArray is called several time (2 and 4th line).
<script>
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
Also you should correct the < to > in your if condition because it seems that it will always be true.
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
I have a HTML table with 2 columns, 5 rows.
you can do this:
function findMyRow(el)(){
if(!el.parentNode) return null;
else if(el.parentNode.tagName.toLowerCase()=="tr") return el.parentNode;
else return findMyRow(el.parentNode);
}
for(var i=0;i<tbl.rows.length;i++){
tbl.rows[i].onclick = function(e){
var selectedRow = null;
if(e.target.tagName.toLowerCase()=="tr") selectedRow = e.target;
selectedRow = findMyRow(e.target);
//this is just for preventing false event raising
if(!selectedRow) return false;
var rowIndex = Array.prototype.indexOf.call(tbl.rows, selectedRow);
for(car j=0;j<selectedRow.cells.length;j++){
var cell = selectedRow.cells[j];
//let's say your inputs each has an unique ID based on your columns index
//like <input id="cellData0" ttype="text" />
//or <input id="cellData1" ttype="text" /> and so on
document.getElementById("cellData" + j).value = cell.innerText;
}
}
}
although you can do this more easier than with jQuery.
With Jquery you could do something like:
$(document).ready(function(){
window.rowIndex = 0; // gobal variable
function displayRow(){
var tableRows = $('#mytable tr');
if(tableRows.length <= window.rowIndex) {
window.rowIndex = 0;
}
var rowCells = $(tableRows[window.rowIndex]).find('td');
$('.cellone').val($(rowCells[0]).html());
$('.celltwo').val($(rowCells[1]).html());
window.rowIndex = window.rowIndex + 1;
};
$('.next').click(function(event){ displayRow(); });
displayRow();
});
There is a live demo here Hope it helps!
Using jQuery, how would you figure out how many columns are in a table?
<script>
alert($('table').columnCount());
</script>
<table>
<tr>
<td>spans one column</td>
<td colspan="2">spans two columns</td>
<td colspan="3">spans three columns</td>
<tr>
</table>
The total number of columns in this example is 6. How could I determine this using jQuery?
Here you go:
jsFiddle
$(function() {
var colCount = 0;
$('tr:nth-child(1) td').each(function () {
if ($(this).attr('colspan')) {
colCount += +$(this).attr('colspan');
} else {
colCount++;
}
});
});
$("table").find("tr:first td").length;
I edited as I didn't realize you were counting the colspan's.
If you want to include using colspan try a loop through the td's in the first row:
var cols = $("table").find("tr:first td");
var count = 0;
for(var i = 0; i < cols.length; i++)
{
var colspan = cols.eq(i).attr("colspan");
if( colspan && colspan > 1)
{
count += colspan;
}else{
count++;
}
}
This is the cleanest in my opinion. It handles tables within tables. And is short and simple:
$("table > tbody > tr:first > td").length
In POJS (Plain Old JavaScript):
HTML:
<table id="foo">
<thead></thead>
<tbody>
<tr>
<td>1</td>
<td colspan="2">2</td>
<td colspan="3">3</td>
</tr>
</tbody>
<tfoot></tfoot>
</table>
JS:
var foo = document.getElementById("foo"), i = 0, j = 0, row, cell, numCols = 0;
//loop through HTMLTableElement.rows (includes thead, tbody, tfoot)
for(i;i<foo.rows.length;i++)
{
row = foo.rows[i];
//loop through HTMLTableRowElement.cells
for(j = 0;j<row.cells.length;j++)
{
cell = row.cells[j];
numCols += cell.colSpan;
cell = null;
}
row = null;
}
alert(numCols) //6;
HTMLTableElement.rows will collect rows from every HTMLTableSectionElement (THead, TBody, and TFoot). Each section also has its own rows HTMLCollection, so you can filter them if need be.
To be robust..I'd do something like this
alert(numCol("table") + " is the max number of cols");
function numCol(table) {
var maxColNum = 0;
var i=0;
var trs = $(table).find("tr");
for ( i=0; i<trs.length; i++ ) {
maxColNum = Math.max(maxColNum, getColForTr(trs[i]));
}
return maxColNum;
}
function getColForTr(tr) {
var tds = $(tr).find("td");
var numCols = 0;
var i=0;
for ( i=0; i<tds.length; i++ ) {
var span = $(tds[i]).attr("colspan");
if ( span )
numCols += parseInt(span);
else {
numCols++;
}
}
return numCols;
}
Just in case we have some funkiness going on between different rows.
http://jsfiddle.net/WvN9u/
Just paying attention to colspan attr
Pass in a table with something like $('foo#table') or $('table:first')
function getColumnCount(e) { //Expects jQuery table object
var c= 0;
e.find('tbody tr:first td').map(function(i,o) { c += ( $(o).attr('colspan') === undefined ? 1 : parseInt($(o).attr('colspan')) ) } );
return c;
}
To circumvent the td/th issue (and also fix a potential issue where attr('colspan') was giving me strings) I went with this:
var colspan = 0;
$('#table').find('tr:first').children().each(function(){
var cs = $(this).attr('colspan');
if(cs > 0){ colspan += Number(cs); }
else{ colspan++; }
});
/**
* Get number of columns in table.
* #param {string} table jQuery selector
* #param {boolean} [malformed=false] whether to inspect each row of malformed table;
* may take some time for large tables
* #returns {?number} number of columns in table, null if table not found.
*/
function getTableColumnsCount(table, malformed) {
malformed = malformed || false;
var $table = $(table);
if (!$table.length) {
return null;
}
var rows = $table.children('thead, tfoot, tbody').children('tr');
if (!malformed) {
// for correct tables one row is enough
rows = rows.first();
}
var maxCount = 0;
rows.each(function () {
var currentCount = 0;
$(this).children('th, td').each(function () {
currentCount += this.colSpan;
});
maxCount = Math.max(maxCount, currentCount);
});
return maxCount;
}
See in action https://jsfiddle.net/kqv7hdg5.
Takes colspan into account.
Works for nested tables.
Works for <thead>, <tfoot>, <tbody>.
Works for mix of <th> and <td>.
Works for malformed tables.
Slightly modified version for those who would like to pass jQuery object instead of selector https://jsfiddle.net/5jL5kqp5.
You have to set an ID to the header row:
<table>
<tr id="headerRow">
<td>spans one column</td>
<td colspan="2">spans two columns</td>
<td colspan="3">spans three columns</td>
</tr>
</table>
And then you can use the following function:
function getColumnCount(headerRowId) {
var columnCount = 0;
$('#' + headerRowId + ' > td').each(function() {
var colspanValue = $(this).attr('colspan');
if (colspanValue == undefined) {
columnCount++;
} else {
columnCount = columnCount + parseInt(colspanValue);
}
});
return columnCount;
}
I simplified answer of Craig M.
And modified to apply to both td and th tag.
function GetColumnCount($Table)
{
var ColCount = 0;
$Table.find("tr").eq(0).find("th,td").each(function ()
{
ColCount += $(this).attr("colspan") ? parseInt($(this).attr("colspan")) : 1;
});
return ColCount;
}
var foo = document.getElementById("price-test-table")
foo.tBodies["0"].firstElementChild.children.length
Give your table an id name
Assume your rows all have the same amount of columns and you have a table body
Use above code, which I think is the simplest on here, similar to first answer
but provides a little more detail
With jQuery and reduce it could look like this:
$.fn.tableCellCount = function() {
return $(this).find('tr:first td, tr:first th').get().reduce(function(a,b) {
return a + ($(b).attr('colspan') ? parseInt($(b).attr('colspan')) : 1);
},0)
}
$('table').tableCellCount();
Or even simpler:
$.fn.tableCellCount = function() {
return $(this).find('tr:first td, tr:first th').get().reduce(function(a,b) {
return a + (b.colSpan ? parseInt(b.colSpan) : 1);
},0)
}
$('table').tableCellCount();
This is the simple solution I have done:
In case you are using TR change TH for TR.
Using JQUERY:
<script>
$(document).ready(function() {
var number = $("table > tbody > tr:first > th").length;
for(var i=0; i <= number; i++){
$('th:nth-child('+ i +')').hide();
}
});
</script>
One Line:
$('.table-responsive tr th').children().length;
function(){
num_columns = 0;
$("table td]").each(function(){
num_columns = num_columns + ($(this).attr('colspan') == undefined ? 1 : $(this).attr('colspan'));
});
return num_columns;
}
I have some tr elements in table:
<table>
<tr id="tr_level_1">...</tr>
<tr id="tr_level_2">...</tr>
<tr id="tr_level_3">...</tr>
<tr id="tr_level_4">...</tr>
<tr id="tr_level_5">...</tr>
</table>
In Javascript I have the next variable:
var levels = 3;
I want to delete all tr's where number in id is more than levels. And if levels is more than number of tr's - adding tr's after last.
Thanls a lot.
Working demo
Try this:
var levels = 3;
$("table tr:gt("+(levels-1)+")").remove();
I substract one because this expression ("gt": greater than) is 0-based index.
For the second part of your question try this:
http://www.jsfiddle.net/dactivo/fADHL/
if($("table tr").length<levels){
//the code here for less than levels
}
else
{
$("table tr:gt("+(levels-1)+")").remove();
}
I think this should complete the answer
var levels = 3;
var $trs = $("table tr");
var currentLevels = $trs.length;
if (currentLevels > levels) {
$trs.filter(":gt(" + (levels - 1) + ")").remove();
} else if (currentLevels < levels) {
var t = "";
for (i = (currentLevels + 1); i <= levels; i++) {
t += '<tr id="tr_level_' + i + '"><td>' + i + '</td></tr>';
}
$trs.parent().after(t);
}
http://jsfiddle.net/c6XWN/1/ <-- levels = 10
http://jsfiddle.net/c6XWN/2/ <-- levels = 5
http://jsfiddle.net/c6XWN/3/ <-- levels = 3
Good luck!
try this
var total = $("#table").find('tr').length;
var levels = 3;
if(levels<=total) {
for(levels=levels;levels<=total;levels++) {
$("#tr_level_"+levels).remove();
}
}
else {
$("#table").append("<tr id=\"tr_level_"+total+1+"\">..</tr>");
// this will add the element with tr_level_6 at the end
}
Maybe this:
function editTr(inVal) {
selector = new RegExp("\d")
var lastID = selector.exec($("table tr").last().attr("id"));
if (lastID > inVal) {
$("table tr").each(function () {
if (selector.exec($(this).attr("id")) > inVal) {
$(this).remove();
}
});
}
else if (lastID < inVal) {
for (x=lastID;x<=inVal;x++) {
$("table").append("<tr id=\"tr_level_"+x+"\"></tr>")
}
}
else {
return null
}
}
var levels = 5;
var lastTr = $('#ranks_percentages tr:last').attr('id');
lastTr = lastTr.split('_');
var lastLevel = lastTr[1];
if (levels < lastLevel) {
//removing
} else {
//adding
}