Internet Explorer 8 & 7 is converting tabs to spaces - javascript

I'm trying to use javascript with jQuery to convert a tab delimited string to html table.
In the input string rows are separated by <br/> and columns by tabs.
Here's what I have so far:
$(function(){
$('div.jstable').each(function(){
var text = $(this).html();
var rows = text.split(/<br>/i);
var htmlString = "<table class='display dataTable'>"
var startTbody = true;
for(i = 0; i< rows.length; i++){
// build header section
if (i == 0){
htmlString += '<thead>';
}else {
if (startTbody){
htmlString += '<tbody>';
startTbody = false;
}
}
htmlString += '<tr>';
var row = rows[i];
var columns = row.split('\t');
// build columns
for (j = 0; j < columns.length; j++ ){
if (i == 0){
htmlString += '<th>' + columns[j] + '</th>';
}else {
htmlString += '<td>' + columns[j] + '</td>';
}
}
htmlString += '</tr>';
if (i == 0){
htmlString += '</thead>'
} else {
if (i == rows.length - 1){
htmlString += '</tbody>'
}
}
}
htmlString += '</table>';
$(this).html(htmlString);
})
});
And here is the input text:
<div class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</div>
Unfortunately in IE8/7 the text returned by jquery .html() function has all tabs replaced by spaces.
IE9 is fine, also current versions of Firefox & Chrome work fine.
Any ideas?

You can pass a regular expression to split(). /\s+/ will consider consecutive whitespace of any kind as a single delimiter:
>>> "one two".split(/\s+/)
["one", "two"]
>>> "one\ttwo".split(/\s+/)
["one", "two"]
>>> "one\ntwo".split(/\s+/)
["one", "two"]

FWIW I found out that if I surround the input text with <pre> tags the .html() function will return the text with tabs in IE7/8, as expected.
So, the initial example source html will look like this:
<pre class="jstable" style="float: left">
col1 col2 col3<br />asda fd dfs<br />mmmm ffff ssss
</pre>

Related

Dynamically add bootstrap rows using modulo

I a trying to dynamically add rows and populate them with 3 col-sm-4 using a modulo against the number of objects in a returned object from a function.
Code:
function formatSeriesCard(series) {
var card = "";
console.log(countProperties(series));
for (var i=0; i < countProperties(series); i++) {
if (i % 3 == 0 ) {
card += "<div class=\"row\">";
}
card += "<div class='col-sm-4' data-id="+i+">";
card += "<div class='action-box'>";
card += "<h4>" + '"' + series.name + '"' + "</h4>";
card += "<p>";
Instead I'm getting each row nested within the previous. Thinking I need to test for the first one and last one. Thanks.
Here is something like what you want
Bootply : http://www.bootply.com/2xnJBpyVsS
JS :
var wantedcol=14;
var mycol='<div class="col-xs-4">mycol</div>';
var startRowLabel="<div class='row'>";
var endRowLabel="</div>";
var start = "";
var end="";
var toAppend="";
for(var i=0; i<wantedcol; i++){
start="";
if(i%3==0 || i==0){
start=startRowLabel;
}
end="";
if(i!=0 && (i%3==2 || i==wantedcol-1)){
end=endRowLabel;
}
console.log(start+mycol+end);
toAppend+=start+mycol+end;
}
$('.container').append(toAppend);
HTML:
<div class="container"></div>
Comment :
You just have to take care about when you have to insert the div.row opening and closing tags

Sorting &Pagination for html table

Am using this Json to Html table and am getting the values also. All I need to do is implement sorting for this. Can someone help me out?
where in the objArray am passing my Json data.
All I need to do is implement Sorting and pagination. Please help me out.
function CreateTableViewX(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + array[i][index] + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
Try Jquery datatable
All you need is to refer Jquery and datables Script files in your solution, select your html table using an Id or class name and Initialize it like this. Datatable will then take care of sorting and pagination for you.
$(document).ready(function(){
$('#tableID').dataTable();
});

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

Find the value of html table cell by passing column name for a particular row

I am dynamically creating a table using JSON so i dont know in advance how many column and/or rows will be generated.
I add a clicked event for the row that get selected.
Now my every table will have a column name ID
I want to find the value of ID for the selected row.
How can i achieve this?
I have googled a find a lot of sample which select the cell be index but not by column name.
My table is something like:
My table is generated like:
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
for (var index in array[i]) {
str += '<td>' + val(array[i][index]) + '</td>';
}
str += '</tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
Any help is appreciated
I hope i understood you correctly but this should do it.
It alerts the content of the td with the name ID of the clicked tr.
$('tr').live('click',function(){
alert( $(this).find('td[name="ID"]').html() );
});
To find the td via the th with text ID you could do this:
var index = $('yourtable th:contains("ID")').index();
alert( $('.selectedRow td:eq('+index+')').html() );
What I would do though is to save the ID in the TR's data object so you won't have to pull it out the td but can access it directly, like this:
[...]
<tr data-id="26"><td>.....</td></tr>
[...]
then you can access it like that:
$('.selectedRow').data('id');

jQuery grid that is tiled

I was hoping some would know how to tile a grid across. I have some code to get started
1 | 2
3 | 4
5 | 6
and in my ajax function
$.ajax({
complete:function(result) {
// in here i want to tile across two sets of td's for each tr
for(var i = 0; i < products.length; i++) {
$('#products').append('<tr><td>' + products[i].Title + '</td></tr>');
}
}
});
<table id="products"></table>
This works whatever the products size is (even or odd).
Hope with comments make it easy to understand
var table_body = '< tbody>';
for(var i = 0; i < products.length; i++) {
if(i%2==0)//if even we open a row
table_body += '<tr>';
//We always put a value
table_body += '<td>' + products[i].Title + '</td>';
if(i%2!=0 || (i==products.length-1))//if odd we close a row
table_body += '</tr>';
}
table_body += '< /tbody>';
$('#products').append(table_body);
Here is a sample code of what you are trying to achieve. You can optimize it to suit your needs. Fiddle
for(var i = 0, y=0; i < 10; i++){
if(y == 0){
$('table').html($('table').html() + '<tr>');
}
$('table').append('<td>' + i + '</td>')
y++;
if( y == 2 ){
y = 0;
$('table').html($('table').html() + '</tr>');
}
}
The simplest solution is to simply not use a table. Chances are if you're arranging data this way, it's not tabular data anyway. I recommend using display: inline-block on your elements and using an HTML element that makes sense for the data you're using, like a ul or li.
This will work for even or odd numbers of elements, fully tested.
var tbl = "";
for (var i = 0; i < products.length; ++i) {
if (i % 2 == 0) tbl += '<tr>';
tbl += '<td>' + products[i].Title + '</td>';
if (i % 2 == 1) tbl += '</tr>';
}
if (i % 2 == 1) tbl += '</tr>';
$("#products").append(tbl);
fiddle

Categories