Table content does not display when using javascript array? - javascript

Below is my code but it does not work yet. What should I do to fix it?
See in particular function showtbl();
My real problem is in function showtbl(); which does not display the contents of the table.
var tampilqr = function (kode) {
var url = 'http://www.playstore.co.id/p/download.html?qr='
var urlfix = url + kode
var keluar = '<a style="float:right;color:#999;text-decoration:none;background:#fff;width:20px;text-align:center;font-weight:bold;" onclick="rem();">X</a><br>'
var cek = keluar + '<iframe src="' + urlfix + '"></iframe>'
if (jscd.os == 'Android') {
window.location.href = urlfix;
} else {
uglipop({
class: 'dl',
source: 'html',
content: cek
});
}
}
var tampilss = function (kode) {
var url = 'https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/detil.html?ss='
var urlfix = url + kode
var keluar = '<a style="float:right;color:#999;text-decoration:none;background:#fff;width:20px;text-align:center;font-weight:bold;" onclick="rem();">X</a><br>'
var cek = keluar + '<iframe src="' + urlfix + '"></iframe>'
uglipop({
class: 'ss',
source: 'html',
content: cek
});
}
var rem = function () {
remove();
}
function tulis() {
document.getElementById("cari").placeholder = "cari aplikasi";
if (on_index = true) {
window.location = window.location.pathname + '?apps='
}
}
function showtbl() {
var img = "<img src='logo/"
var imgt = ".png'/>"
var li = "<br /> Link: <a href='?apps="
var lin = "'>http://playstore.co.id/?apps="
var link = "</a><br /> Terbit: "
var b = "<button type='button' class='btn btn-danger' onclick='tampilss(""
var bt = "");'>Screenshoot</button><br><button type='button' class='btn btn-success' onclick='tampilqr(""
var btn = "");'>Download</button>"
var A1 = "ss-clothes"
var A2 = "korselindo"
var A3 = "real-hiphop-shop"
/* if HTML, it must be:
<tr>
<td><img src="logo/ss-clothes.png" /></td>
<td>SS-Clothes<br /> Link: http://playstore.co.id?apps=ss-clothes<br /> Terbit: 23-06-2015</td>
<td><button class="btn btn-danger" onclick="tampilss("ss-clothes");" type="button">Screenshoot</button><br />
<button class="btn btn-success" onclick="tampilqr("ss-clothes");" type="button">Download</button></td>
</tr>
*/
var values = new Array(3);
values[1] = [img + A1 + imgt, A1 + li + A1 + lin + A1 + link, b + A1 + bt + A1 + btn];
values[2] = [img + A2 + imgt, A2 + li + A2 + lin + A2 + link, b + A2 + bt + A2 + btn];
values[3] = [img + A3 + imgt, A3 + li + A3 + lin + A3 + link, b + A3 + bt + A3 + btn];
var myTable = document.getElementById("myTable");
// IE7 only supports appending rows to tbody
var tbody = document.createElement("tbody");
// for each outer array row
for (var i = 1; i < values.length; i++) {
var tr = document.createElement("tr");
// for each inner array cell
// create td then text, append
for (var j = 0; j < values[i].length; j++) {
var td = document.createElement("td");
var txt = document.createElement("span");
txt.innerHTML = values[i][j];
td.appendChild(txt);
tr.appendChild(td);
}
// append row to table
// IE7 requires append row to tbody, append tbody to table
tbody.appendChild(tr);
myTable.appendChild(tbody);
}
}
<!DOCTYPE html>
<html class="no-js">
<head>
<meta charset="UTF-8">
<title>Download Aplikasi</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<meta name="description" content="Toko aplikasi android Indonesia, apptoko, download aplikasi android .apk, appstore alternatif Google play store android market">
<link href="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/css/style.css" rel="stylesheet" />
<script src='https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/js/modernizr.js'></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/js/jquery.dataTables.js"></script>
<link href="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/css/jquery.dataTables.min.css" rel="stylesheet" />
<script async="" src="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/js/bootstrap.min.js"></script>
<script async="" src="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/js/os.js"></script>
<link href="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/css/uglipop.css" rel="stylesheet" />
<script async="" src="https://dfe4876b91450c3efbab76e8d43c4a665e738138-www.googledrive.com/host/0B94BKN-oncxmfllMNlZkWGJTaF9QWmtLOVktR3djU3B0NGJuTFVwS2tDMS1jYzZkNEN6Y00/js/uglipop.js"></script>
</head>
<body onLoad="tulis();showtbl();">
<div id="atas">
<img src="http://1.bp.blogspot.com/-UON5Z5IIOus/VdH_gr8XRXI/AAAAAAAAAbY/Q-I4QfbZr9U/s1600/playstore-indonesia-logo.gif" />
</div>
<table class="table table-striped" id="myTable">
<thead>
<tr>
<th>Logo</th>
<th>Nama App</th>
<th>Tindakan</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
<script>
$(document).ready(function () {
$("img").error(function () {
$(this).hide();
});
var table = $('#myTable').dataTable({
"oSearch": {
"sSearch": $.urlParam('apps'),
responsive: true
},
});
});
$.urlParam = function (name) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results && results[1].replace(/(^\s+|[^a-zA-Z ]+|\s+$)/g, ' ');
return results && results[1].replace(/\s+/g, ' ');
if (!results) {
return '//';
}
return results[1] || '';
};
</script>
</body>
</html>
My real problem is in function showtbl(); which does not display the contents of the table.
Please run the code. What should I do to fix it?

My real problem is in function showtbl(); which does not display the
contents of the table.
If you remove the irrelevant empty <tbody><tr></tr></tbody> it works :
http://jsfiddle.net/yujpozf9/1/
dataTables does not like multiple <tbody> elements, and certainly not <tbody> elements with an odd number of columns (like none).
Also move responsive: true out to where it belongs and remove the trailing ' - you seem to have a lot of focus on IE7, trailing quotes is a IE7-killer.
var table = $('#myTable').dataTable({
responsive: true,
"oSearch": {
//"sSearch": $.urlParam('apps')
}
});
have commented out $.urlParam since this is not the main issue, and I not fully understand what you are trying to do. Your code is one of the most peculiar uses of dataTables I have ever seen (no offense!) - try read about column rendering, I think you will be much happier doing it this way -> https://datatables.net/examples/advanced_init/column_render.html - the official examples in general.
Also, instead of using google drive, you can use the dataTables CDN - much easier to maintain and change versions. I have noticed you are using v1.10.2 :
<script type="text/javascript" src="//cdn.datatables.net/1.10.2/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.2/css/jquery.dataTables.min.css"/>

As far as I remember, datatables plugin need well-formatted table to work properly. You need thead and tbody tags as it's specified in the doc (read it carefully : https://www.datatables.net/manual/installation). Once it's done you don't have to write all that code to filter and display what you want.

Related

TypeError when parsing Blogger API response: Cannot read property 'url' of undefined

I'm parsing JSON feed from the blogger API but its throwing following error:
37:59 Uncaught TypeError: Cannot read property 'url' of undefined
Previously it was working fine, there weren't any issues but suddenly the error keeps coming up and nothing is displaying. I have looked for stackoverflow and followed this post as well but the error is not going away. Maybe blogger has changed their object nodes that i can't figure out.
Javascript Code:
<script type="text/javascript">
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/');
var postTimestamp = json.feed.entry[i].published.$t;
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= '+ postTimestamp +'>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
//document.write(item);
document.getElementById("news").appendChild(item);
console.log(item);
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
<div id="news"></div>
JsFiddle: https://jsfiddle.net/645pg9rz/
If you run console.log(json.feed.entry) in your fiddle, you'll see that there is no key called media$thumbnail in the returned objects. That is why your code is failing at var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s640/'); - it is trying to access the url property of an item that doesn't exist.
Perhaps the API used to use that key and no longer does, or there are just no thumbnails available in the entries you requested. I don't see a new key with an image file other than the Blogger logo.
Updated: the pictures you're trying to reach are not in the object that came to you. that's why you get the error. (json.feed.entry[i].media$thumbnail)
there are no pictures in the object that came to you. It's the only icon that comes. I put them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>Document</title>
<style>
</style>
</head>
<body>
<div class="row" id="news"></div>
<script>
function mycallback(json) {
console.log(json)
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, 400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].author[0].gd$image.src;
var postTimestamp = json.feed.entry[i].published.$t;
console.log(postImage)
var item = '<div class="col-md-3 mb-4 blogpost-main">';
var item = item + '<div class="card h-100">';
var item = item + '<img class="card-img-top" src="' + postImage + '"/>';
var item = item + '<div class="card-body">';
var item = item + '' + postTitle + '</h6>';
var item = item + '<p class="card-text text-muted"><i class="far fa-clock" style="color: #888"></i> <time class="timeago" datetime= ' + postTimestamp + '>' + postTimestamp + '</time></p>';
var item = item + '</div>';
var item = item + '</div>';
var item = item + '</div>';
document.getElementById("news").innerHTML += item;
}
}
</script>
<script src="https://www.wallpapersoverflow.com/feeds/posts/summary?orderby=published&max-results=4&alt=json-in-script&callback=mycallback"></script>
</body>
</html>

Change color of table cell in javascript based on other cell's value

I am displaying a table on the webpage as follows:
ID | Val | Num
ABC | Value1 | 1
ABC | Value1 | 0.8
CDB | Value 2 | 0.5
I want that if the cell value in Num column for that row is between 1 and 0.8, then the background color of the corresponding Val column's cell should be red, if between 0.7 to 0.5 then orange, and below it yellow.
I'm using DataTables
Below is my js code:
for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
if (col_id === 2) {
row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
}
else {
row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
}
}
row_html += "</tr>";
$('#' + el + '-table tbody').append(row_html);
}
$('#' + el + '-table').DataTable(datatables_options);
I tried to add the background color to the cell using the style.backgroundColor but I don't think it's working. I added this inside the for loop:
if (col_id === 1) {
if (parseFloat(csv_data[row_id][2]) <= 1 && parseFloat(csv_data[row_id][2]) > 0.7)
{
row_html.style.backgroundColor = 'ec8e8e'
}
}
But it's not working. Could anybody tell me how to do it?? Thanks!
UPDATE:
My csvToHtml.js file:
var CsvToHtmlTable = CsvToHtmlTable || {};
CsvToHtmlTable = {
init: function (options) {
options = options || {};
var csv_path = options.csv_path || "";
var el = options.element || "table-container";
var allow_download = options.allow_download || false;
var csv_options = options.csv_options || {};
var datatables_options = options.datatables_options || {};
var custom_formatting = options.custom_formatting || [];
$("#" + el).html("<table class='table table-striped table-condensed' id='" + el + "-table'></table>");
$.when($.get(csv_path)).then(
function(data){
var csv_data = $.csv.toArrays(data, csv_options);
var table_head = "<thead><tr>";
for (head_id = 0; head_id < csv_data[0].length; head_id++) {
table_head += "<th>" + csv_data[0][head_id] + "</th>";
}
table_head += "</tr></thead>";
$('#' + el + '-table').append(table_head);
$('#' + el + '-table').append("<tbody></tbody>");
for (row_id = 1; row_id < csv_data.length; row_id++) {
var row_html = "<tr>";
//takes in an array of column index and function pairs
if (custom_formatting != []) {
$.each(custom_formatting, function(i, v){
var col_idx = v[0]
var func = v[1];
csv_data[row_id][col_idx]= func(csv_data[row_id][col_idx]);
})
}
for (col_id = 0; col_id < csv_data[row_id].length; col_id++) {
if (col_id === 2) {
row_html += "<td>" + parseFloat(csv_data[row_id][col_id]) + "</td>";
}
else {
row_html += "<td>" + csv_data[row_id][col_id] + "</td>";
}
}
row_html += "</tr>";
$('#' + el + '-table tbody').append(row_html);
}
$('#' + el + '-table').DataTable(datatables_options);
if (allow_download)
$("#" + el).append("<p><a class='btn btn-info' href='" + csv_path + "'><i class='glyphicon glyphicon-download'></i> Download as CSV</a></p>");
});
}
}
My index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CSV to HTML Table</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/dataTables.bootstrap.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script type="text/javascript" src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script type="text/javascript" src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<h2>CSV to HTML Table</h2>
<div id='table-container'></div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.csv.min.js"></script>
<script type="text/javascript" src="js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="js/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="js/csv_to_html_table.js"></script>
<script type="text/javascript">
function format_link(link){
if (link)
return "<a href='" + link + "' target='_blank'>" + link + "</a>";
else
return "";
}
CsvToHtmlTable.init({
csv_path: 'data/fatty_acid_profiles.csv',
element: 'table-container',
allow_download: true,
csv_options: {separator: ','},
datatables_options: {"paging": false},
custom_formatting: [[2, format_link]]
});
</script>
You can append row_html with $(row_html) and apply css to that with your condition.
Here color will be based on your condition.
$('#' + el + '-table tbody').append($(row_html).css('background',color));
Check below sample to get more idea
$(document).ready(function() {
$('#example').dataTable();
var val = 0.1;
var row_html = "<tr>";
row_html += "<td>ADD</td><td>val 4</td><td>" + val + "</td>";
row_html += "</tr>";
var color = "red"; // can be hex value, #ededed
if (val > 0.7) {
color = "orange";
} else if (val < 0.4) {
color = "yellow";
}
$('#example').append($(row_html).css("background-color", color));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<body>
<div class="container">
<table cellpadding="0" cellspacing="0" border="0" class="dataTable" id="example">
<thead>
<tr>
<th>ID</th>
<th>Val</th>
<th>Num</th>
</tr>
</thead>
<tbody>
<tr>
<td>ABC</td>
<td>Value 1</td>
<td>0.5</td>
</tr>
<tr>
<td>BBC</td>
<td>Value 2</td>
<td>0.8</td>
</tr>
<tr>
<td>CBC</td>
<td>Value 3</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
</body>

How to display information relative to image clicked using pokemon API?

I'm trying to get and display the image and information of a clicked pokemon from pokemon API
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script src="pokedex2.js"></script>
<link rel="stylesheet" href="pokedex2.css">
<title>Pokedex v 2.0</title>
</head>
<body>
<div id="all">
<div id="pokemon">
</div>
<div id="chosen">
</div>
</div>
</body>
</html>
JavaScript
$(document).ready(function(){
for(i = 1; i <=151; i ++){
$("#pokemon").append("<img id=pokepic" + i + "
src='http://pokeapi.co/media/img/" + i +
".png'>");
}
var clicked = false;
$("img").click(function(){
clicked = true;
console.log(this);
if(clicked){
$.get("http://pokeapi.co/api/v1/pokemon/" + i +"/", function(data){
var str = "";
str += "<h4>Types</h4>";
str += "<ul>";
var str2 = "";
str2 += "<h4>height</h4>";
str2 += "<ul>";
var str3 = "";
str3 += "<h4>weight</h4>";
str3 += "<ul>";
for(i = 0; i < data.types.length; i ++){
str += "<li>" + data.types[i].name + "</li>";
}
str2 += "<li>" + data.height + "</li>";
str3 += "<li>" + data.weight + "</li>";
str += "</ul>"
str2 += "</ul>"
str3 += "</ul>"
$("#chosen").html(str + str2 + str3); }, "json");
}
else{
clicked = false;
}
})
});
At the moment, the only information being brought up are for the first 3 pokemon in the list, not for the pokemon that was clicked. I need to find the information associated with the clicked pokemon, like a pokedex.
I included console.log to show that whichever image is clicked, the picture, and pokepic ID number associated with that image appear in the console. Instead what I need is for the image and stats associated with each image to appear in the div labeled chosen
Your click event uses the i variable defined in your for loop. Since the function inside the click is always called after the loop is done, i is always 152. You need to read the current pokemon from your click event:
$('img').on('click', function(e){
var pokemonId = e.target.id.split('pokepic')[1];
$.get("http://pokeapi.co/api/v1/pokemon/" + pokemonId +"/", function(data){
...
});
});

Create HTML table with hyperlink from JSON Object

I have an application which returns a JSONObject. I am able to get data from JSON object using below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<head>
<style type="text/css">
table, td, th
{
border:1px collapse black;
font-family:Arial;
font-size :small;
}
th
{
background-color:green;
color:white;
}
.hideMe
{
/*display : none;*/
/*visibility: hidden;*/
}
</style>
<script type="text/javascript" language="jscript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" language="javascript">
var host = "somehost";
var mystr = "http://"+ host +"/rest/bpm/wle/v1/exposed/process"; // use get for this
var ulink = "";
$(document).ready(function () {
$.get(mystr, function (data) {
var obj = JSON.parse(data);
var thtml = "<table id='proctable'>";
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function()' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
}
thtml = thtml + "</table>";
document.getElementById('contentdiv').innerHTML = thtml;
});
});
//javascript
my_function = null;
//jquery
$(function () {
function generateBPDInstance() {
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}
my_function = generateBPDInstance;
ulink = "";
})
`
</script>
</head>
<body>
<form name="myform">
<div id="contentdiv">
<table id="proctable">
</table>
</div>
</form>
</body>
</html>
The above html creates a table showing a list of the returned values. I also want to get rowIndex of hyperlink and pass value of column2 to function generateBPDInstance.
I am not so good at HTML and Jquery. Please suggest how can I get rowIndex for HTML table which is created through javascript.
Thanks in advance.
The simple way is :
change your table building to this
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "" + obj.data.exposedItemsList[i].display + "" + ulink + "";
function my_function(e){
//e is the row index and when you call document.getLementById("proctable").rows[e]; this will give you the complete row.
}
--this is a simple way, and if you want traverse the tree and get , you always have parentnode or you can use jquery $(object).parent() to get the parent of hyperlink and traverse.
You problem is "pass value of column2 to function generateBPDInstance". Why not pass it already while generating the table?
for (i = 0; i < obj.data.exposedItemsList.length; i++) {
ulink = "http://" + host + obj.data.exposedItemsList[i].startURL;
thtml = thtml + "<tr><td><a onclick='my_function('" + ulink + "')' href='javascript:void(0)'>" + obj.data.exposedItemsList[i].display + "</a></td><td id='linkcell' class='hideMe'>" + ulink + "</td></tr>";
// ------------------------------------------------------^ pass the value
}
Add parameter to your function generateBPDInstance
function generateBPDInstance(ulink) {
//--------------------------^----
$.post(ulink, function (taskdata) {
var tobj = JSON.parse(taskdata);
alert(tobj.data.tasks[0].name);
alert(tobj.data.tasks[0].tkiid);
});
}

Drap-n-drop HTML table columns (not rows)

I've found dragtable http://www.danvk.org/wp/dragtable/ but I need a Jquery-based solution. May be I'm missing something?
The plugin jqGrid (latest versions at github repo) has a feature to re-order columns - the documentation is here. It does not appear to have drag/drop support for re-ordering columns however.
Here is a custom working sample of draggable table columns using only jQuery and jQuery UI sortable interaction.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="jquery-ui-1.8.1.custom.css">
<style type="text/css">
th
{
background-color: #e0e0e0;
cursor: pointer;
}
.ui-state-highlight
{
height: 1.5em;
line-height: 1.2em;
}
</style>
<script type="text/javascript">
$(function() {
var $table1 = $('#table1');
var $table1Thead = $table1.find('thead');
var $table1Tbody = $table1.find('tbody');
var maxCols = 10;
var maxRows = 50;
// populate fake data
for (var i = 1; i <= maxCols; i++) {
$table1Thead.append('<th id="column' + i + '">column ' + i + '</th>');
}
var rowHtml;
for (var x = 1; x <= maxRows; x++) {
rowHtml = '<tr>';
for (var i = 1; i <= maxCols; i++) {
//rowHtml += '<td>row ' + x + ', column ' + i + '</td>';
rowHtml += '<td>column ' + i + '</td>';
}
rowHtml += '</tr>';
$table1Tbody.append(rowHtml);
}
// set an index helper on each th element
$table1Thead.find('th').each(function() {
var thElement = $(this);
thElement.data('columnIndex', $table1Thead.find('th').index(thElement));
});
$table1Thead.sortable({
items: 'th',
containment: 'parent',
helper: 'clone',
placeholder: 'ui-state-highlight',
update: function(event, ui) {
var prevPos = ui.item.data('columnIndex');
var newPos = $table1Thead.find('th').index(ui.item);
// adjust all the row elements
$table1Tbody.find('tr').find('td:eq(' + prevPos + ')').each(function() {
var tdElement = $(this);
var tdElementParent = tdElement.parent();
tdElement.remove();
tdElementParent.find('td:eq(' + newPos + ')').before(tdElement);
});
// re-set an helper indexes
$table1Thead.find('th').each(function() {
var thElement = $(this);
thElement.data('columnIndex', $table1Thead.find('th').index(thElement));
});
}
});
});
</script>
</head>
<body>
<table id="table1">
<thead>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>
This JavaScript does drag-and-drop on columns. As it doesn't uses any framework you can combine it easily with any other framework.
Why do you nee a jQuery based solution when you can have one without the need of a specific framework.
Another approach to reorder columns with Jquery UI Sortable:
http://jsfiddle.net/pg7wH/
Needs
jQuery (tested with 1.7.2 - 2.0)
jQuery UI (tested with 1.8.18 - 1.10.2)
HTML:
<button id="getSorting">Get sorting</button><input id="showSorting" />
<table id="table1">
<thead class="ui-state-default"></thead>
<tbody></tbody>
</table>
JS:
$(function() {
var $table1 = $('#table1');
var $table1Thead = $table1.find('thead');
var $table1Tbody = $table1.find('tbody');
var startPos;
var oldPos;
// populate fake data
var maxCols = 10;
var maxRows = 50;
for (var i = 1; i <= maxCols; i++) {
$table1Thead.append('<th sort="' + i + '" id="column[' + i + ']">column ' + i + '</th>');
}
var rowHtml;
for (var x = 1; x <= maxRows; x++) {
rowHtml = '<tr>';
for (var i = 1; i <= maxCols; i++) {
//rowHtml += '<td>' + i + ' - ' + x + '</td>';
rowHtml += '<td>col ' + i + '</td>';
}
rowHtml += '</tr>';
$table1Tbody.append(rowHtml);
}
// Show sorting
$("button#getSorting").click(function() {
$('#showSorting').val($table1Thead.sortable('toArray', { attribute: "sort" } ))
console.log($table1Thead.sortable('toArray', { attribute: "sort" } ))
})
// The sorting
$table1Thead.sortable({
axis: "x" ,
items: 'th',
containment: 'parent',
cursor: 'move',
helper: 'clone',
distance: 5,
opacity: 0.5,
placeholder: 'ui-state-highlight',
start: function(event, ui) {
startPos = $table1Thead.find('th').index(ui.item);
oldPos = startPos;
},
change: function(event, ui) {
// Get position of the placeholder
var newPos = $table1Thead.find('th').index($table1Thead.find('th.ui-state-highlight'));
// If the position is right of the original position, substract it by one in cause of the hidden th
if(newPos>startPos)newPos--;
// move all the row elements
//console.log('Move: 'oldPos+' -> '+newPos);
$table1Tbody.find('tr').find('td:eq(' + oldPos + ')').each(function() {
var tdElement = $(this);
var tdElementParent = tdElement.parent();
if(newPos>oldPos)// Move it the right
tdElementParent.find('td:eq(' + newPos + ')').after(tdElement);
else// Move it the left
tdElementParent.find('td:eq(' + newPos + ')').before(tdElement);
});
oldPos = newPos;
}
});
});
Thanks to Nate Pinchot for his example.

Categories