Moving Javascript variables into Html Table - javascript

i found this guide to create a stock ticker.
I tried to change it into an html table, but i'm stuck.
So, i created the table, but i have big problems to divide each variable.
What i want to accomplish is a table with this columns order:
Symbol: CompName
Price: Price
Change: PriceIcon + ChnageInPrice
%: PercentChnageInPrice
What i've accomplished for now it's just this, all the content in one column (because of the variable StockTickerHTML i guess)
Full Code Link
Can you please help me?
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerHTML = "";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function () {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function () {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function () {
Price = $(this).text();
});
$(this).find("Change").each(function () {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function () {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText", PriceIcon="up_green";
if(parseFloat(ChnageInPrice) < 0) { PriceClass = "RedText"; PriceIcon="down_red"; }
StockTickerHTML = StockTickerHTML + "<span class='" + PriceClass + "'>";
StockTickerHTML = StockTickerHTML + "<span class='quote'>" + CompName + " </span> ";
StockTickerHTML = StockTickerHTML + parseFloat(Price).toFixed(2) + " ";
StockTickerHTML = StockTickerHTML + "<span class='" + PriceIcon + "'></span>" + parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + " (";
StockTickerHTML = StockTickerHTML + parseFloat( Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%)</span> </br>";
});
$("#dvStockTicker").html(StockTickerHTML);
$("#dvStockTicker").jStockTicker({interval: 30, speed: 2});
});
}

One solution could be this :
(see comments in code)
$(window).load(function() {
StockPriceTicker();
setInterval(function() {
StockPriceTicker();
}, 2 * 1000); // <------ we refresh each 2 seconds
});
// we get the table's body where
// the lines will be inserted.
var $body = $('table tbody');
/*
this will be the cache of
our lines, once they are prepared / transformed
as your need, we will join and insert them
in the body of our table.
*/
var Lines = [];
/*
We define a function in charge of creating the HTML
of each row of hour table, and then push them
in the array defined above "Lines".
*/
var addLine = function(symbol, price, change, percent) {
Lines.push('<tr>' +
'<td class="symbol" >' + symbol + '</td>' +
'<td class="price" >' + price + '</td>' +
'<td class="change" >' + change + '</td>' +
'<td class="percent">' + percent + '</td>' +
'</tr>');
};
// this is your function to get data
function StockPriceTicker() {
var Symbol = "",
CompName = "",
Price = "",
ChnageInPrice = "",
PercentChnageInPrice = "";
var CNames = "^FTSE,FTSEMIB.MI,^IXIC,^N225,^HSI,EURUSD=X";
var flickerAPI = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + CNames + "%22)&env=store://datatables.org/alltableswithkeys";
var StockTickerXML = $.get(flickerAPI, function(xml) {
$(xml).find("quote").each(function() {
Symbol = $(this).attr("symbol");
$(this).find("Name").each(function() {
CompName = $(this).text();
});
$(this).find("LastTradePriceOnly").each(function() {
Price = $(this).text();
});
$(this).find("Change").each(function() {
ChnageInPrice = $(this).text();
});
$(this).find("PercentChange").each(function() {
PercentChnageInPrice = $(this).text();
});
var PriceClass = "GreenText",
PriceIcon = "up_green";
if (parseFloat(ChnageInPrice) < 0) {
PriceClass = "RedText";
PriceIcon = "down_red";
}
/*
We create the html to be inserted on each xml loop.
- First : prepare and transform as you need
- Last : use the function we define above "addLine";
*/
var htmlSymbol,
htmlPrice,
htmlChange,
htmlPercent;
htmlSymbol = "<span class='" + PriceClass + "'>";
htmlSymbol = htmlSymbol + "<span class='quote'>" + CompName + " </span></span>";
htmlPrice = parseFloat(Price).toFixed(2) + " ";
htmlChange = parseFloat(Math.abs(ChnageInPrice)).toFixed(2) + "<span class='" + PriceIcon + "'></span>";
htmlPercent = parseFloat(Math.abs(PercentChnageInPrice.split('%')[0])).toFixed(2) + "%";
// We use here the function defined above.
addLine(htmlSymbol, htmlPrice, htmlChange, htmlPercent);
});
/*
Once the loop of reading the XML
end, we have pushed all html in the array "Lines".
So now we delete the content of our table's body, and
we fill it with all the lines joined.
*/
$body.empty().html(Lines.join(''));
// we reset the content of Lines for the next interval
Lines = [];
});
}
.GreenText {
color: Green;
}
.RedText {
color: Red;
}
.up_green {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/up.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
.down_red {
background: url(http://www.codescratcher.com/wp-content/uploads/2014/11/down.gif) no-repeat left center;
padding-left: 10px;
margin-right: 5px;
margin-left: 5px;
}
table {
border: solid;
border-color: #666;
}
td {
padding: 3px;
}
.symbol {
border: solid 3px #DDD;
}
.price {
border: solid 3px aqua;
}
.change {
border: solid 3px yellow;
}
.percent {
border: solid 3px purple;
}
td.price,
td.change,
td.percent {
text-align: right;
}
tbody tr:nth-child(odd){
background-color:#EEF;
}
tbody tr:nth-child(even){
background-color:#AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<thead>
<tr>
<th class='symbol'>Symbol</th>
<th class='price'>Price</th>
<th class='change'>Change</th>
<th class='percent'>%</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

Related

Trouble with script-generated dynamic html element

I developing comment section for my HTMl page. I place it in div container in body section in my page, like that:
<body>
...
<div id='commentsTree'></div>
...
</body>
Commment section generated by script, here it is
function createCommentsTree(commentsData) {
resultHTML = "";
let commentsArray = JSON.parse(commentsData);
//let result = "";
resultHTML = resultHTML + "<ul id='myUL'>";
commentsArray.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
});
resultHTML = resultHTML + "</ul>";
return resultHTML;
}
function createCommentsTreeHyerarchycally(source) {
resultHTML = resultHTML + "<ul class='nested'>";
source.subordinates.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
})
resultHTML = resultHTML + "</ul>";
}
in result i have hyerarchycally comments tree, you can see it on example here
https://jsfiddle.net/Obliterator/wogurs6L/, or, on picture "comment section" added below.
On picture you can see "caret" symbol, looks like black small arrow near textareas, i mark it on picture. When i click it, comment line must unfold, and show subordinate comment lines. You can try it in example here https://jsfiddle.net/Obliterator/wogurs6L/, in this example it works totally correct. But, in my web page, when i click on "caret" symbol, nohing happens, comment line do not unfold. And this is a problem.
For unfold by clicking "caret" symbol i make this script and css:
script:
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
css:
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
.textFieldRoot {
position: relative;
left: 15px;
width: 100%;
}
.textField {
position: relative;
width: 100%;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
position: absolute;
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
vertical-align: top;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
i add css and script in my page, for which i trying add comment section, that way (treeListScript.js and treeListStyle.css):
<head>
...
<script type="text/javascript" src="http://localhost/testapp/lib/others/treeList/treeListScript.js"></script>
<link rel="stylesheet" href="http://localhost/testapp/lib/others/treeList/treeListStyle.css">
...
</head>
<body>
...
<div id='commentsTree'></div>
...
</body>
i create my web page this way:
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
line windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments); creates comment section.
So, what i am doing wrong, what i mus do for my unfold fucntional works correct on my web page? If something unclear, ask, i try explain.
I solve problem by myself. Reason is i just incorrect add event handler to the .caretelements, i add it as script in head section, but i need to add it after i generate comment section, this way:
//creating new HTML page +++
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
//creating new HTML page ---
//creating comment section +++
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
//creating comment section ---
//adding event handler +++
var toggler = windowTask.document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
//adding event handler ---
now everything works fine. If anyone spend some time for my question, thx.

How to storage values in local storage using jquery?

How can dynamic values be stored in the local storage?
I have a seat layout. How i can store only the selected seat numbers in the local storage, but not reserved seats?
My code can be seen below:
$(function() {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
var SeatNo = document.getElementById('place').value;
localStorage.setItem('SeatNum', SeatNo);
};
//case I: Show from starting
//init();
//Case II: If already booked
var bookedSeats = [5, 10, 25];
init(bookedSeats);
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('This seat is already reserved');
} else {
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function() {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function() {
var str = [],
item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function(index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>
localStorage is an object within the global 'window' object, and therefore will normally be available throughout your javascript code. It pretty much behaves like a dictionary, you create, retrieve, edit and remove key:value pairs. jQuery will not be necessary.
It is also imporant to remember that localStorage only support string values, and simply saving an array would not work.
// When modifying bookedSeats:
var bookedSeatsCacheString = JSON.stringify(bookedSeats);
localStorage.setItem('bookedSeats', bookedSeatsCacheString);
// Init code:
var bookedSeatsCache = localStorage.getItem('bookedSeats');
var bookedSeats = JSON.parse(bookedSeatsCache);
if(!Array.isArray(bookSeats))
bookedSeats = [];
init(bookedSeats);
EDIT: I edited your code to make this work with localStorage
$(function () {
var settings = {
rows: 6,
cols: 10,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
var init = function (reservedSeat) {
var str = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(str.join(''));
};
// Init code
var bookedSeatsCache = localStorage.getItem('bookedSeats'),
bookedSeats;
if(typeof bookedSeatsCache === 'string' && bookedSeatsCache.length > 0)
bookedSeats = JSON.parse(bookedSeatsCache);
else
bookedSeats = [];
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved');
}
else{
var seatNum = $(this).attr('title');
bookedSeats.push(seatNum);
localStorage.setItem('bookedSeats', JSON.stringify(bookedSeats));
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
alert(str.join(','));
})
});
#holder{
height:225px;
width:365px;
background-color:#F5F5F5;
border:1px solid #A4A4A4;
margin-left:10px;
}
#place {
position:relative;
margin:7px;
}
#place a{
font-size:0.6em;
}
#place li
{
list-style: none outside none;
position: absolute;
}
#place li:hover
{
background-color:yellow;
}
#place .seat{
background:url("available_seat_img.gif") no-repeat scroll 0 0 transparent;
height:33px;
width:33px;
display:block;
padding:5px;
}
#place .selectedSeat
{
background-image:url("booked_seat_img.gif");
}
#place .selectingSeat
{
background-image:url("selected_seat_img.gif");
}
#place .row-3, #place .row-4{
margin-top:10px;
}
#seatDescription li{
vertical-align: middle;
list-style: none outside none;
color:white;
font-family:'LatoWeb', 'Lucida Grande', 'Lucida Sans Unicode', Arial, sans-serif;
font-size:13px;
padding-left:28px;
padding-top:14px;
height:35px;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="">
<ul id="seatDescription">
<li style="background:url('available_seat_img.gif') no-repeat scroll 0 0 transparent;">Available Seat</li>
<li style="background:url('booked_seat_img.gif') no-repeat scroll 0 0 transparent;">Booked Seat</li>
<li style="background:url('selected_seat_img.gif') no-repeat scroll 0 0 transparent;">Selected Seat</li>
</ul>
</div>
<div style="width:100%">
<input type="button" id="btnShowNew" value="Show Selected Seats" />
<input type="button" id="btnShow" value="Show All" />
</div>
</div>

Loop JSON using JavaScript and create dynamic HTML table

I'm trying to loop through a JSON object from a REST endpoint. I've successfully iterated through the JSON array and created a dynamic table based on the variables I created from the JSON object.
The issues I'm having is creating a separate table for each location. For example, I would like each location to be their own row, and the associated camera position with its photo as separate cells. Instead, my table is coming out as one column, one row.
Here is what my code looks like (please disregard my amateur coding abilities, as I'm still learning) :) :
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function createLocationTable() {
var features = getAllLocations();
var site_number = '';
var sitename = '';
var cameraPostion = '';
var imgURL = '';
var date = new Date();
var content = '';
content = '<table align="center">';
content += '<tr><th class="table-header">';
content += '<center>RWIS Images</center></th></tr></table>'
content += '<table><tbody>';
var tempSiteName = features[0].attributes.SITE_NUMBER;
content += '<tr>';
for (var i = 0; i < features.length; i++) {
site_number = features[i].attributes.SITE_NUMBER
sitename = features[i].attributes.RPUID_NAME;
cameraPostion = features[i].attributes.CAMERA_POSITION;
imgURL = features[i].attributes.IMAGE_URL;
//if(tempSiteName.toString().substr(0,tempSiteName.toString().indexOf(' ')) != sitename.toString().substr(0,sitename.toString().indexOf(' ')))
if (tempSiteName != sitename) {
//then create a new row
tempSiteName = sitename;
content += '</tr>';
content += '<tr>';
}
//otherwise everythind goes side to side
content += '<td><center><b><br>' + sitename + '</b> -</br></center><center>' + cameraPostion +'</center>';
content += '<div><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +
' class="imgRWIS" height="100" width="150"></center></div></td>';
}
content += '</tbody></table>';
document.write(content)
return content;
}
window.onload = createLocationTable();
body {
font-family: Arial, 'Trebuchet MS', Verdana, Helvetica, sans-serif;
}
.table-header {
font-size: 24px;
font-family: Arial, sans-serif;
color: #d46200;
}
.sitename h{
font-size: 20px;
font-family: Arial, sans-serif;
color: #7c9f3d;
}
.table-location {
/* background: #dddddd; */
width: auto;
margin: 10px 0;
font-size: 14px;
border: 1px solid black;
}
.table-location td {
padding: 5px;
}
img.imgRWIS {
background: black;
position: relative;
padding: 1px;
display: block;
margin: 0 auto;
}
From what i understand this is what you want
function getJSON(url) {
var resp = '';
var xmlHttp = new XMLHttpRequest();
if (xmlHttp != null) {
xmlHttp.open("GET", url, false);
xmlHttp.send(null);
resp = xmlHttp.responseText;
}
return resp;
}
function getAllLocations() {
gjson = getJSON(
'https://gis.iowadot.gov/public/rest/services/Maintenance/RWIS_Data/FeatureServer/5/query?where=1%3D1&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&distance=&units=esriSRUnit_Foot&relationParam=&outFields=CAMERA_POSITION%2C+SITE_NUMBER%2C+RPUID_NAME%2C+IMAGE_URL&returnGeometry=true&maxAllowableOffset=&geometryPrecision=&outSR=&gdbVersion=&returnDistinctValues=false&returnIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&orderByFields=RPUID_NAME+ASC%2C+CAMERA_POSITION+ASC&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&multipatchOption=&resultOffset=&resultRecordCount=&f=pjson'
);
var parsedJSON = JSON.parse(gjson);
var features = parsedJSON.features;
return features;
}
/*
creates the table.
*/
function createLocationTable() {
var features = getAllLocations();
var site_number = '';
var sitename = '';
var cameraPostion = '';
var imgURL = '';
var date = new Date();
var content = '';
content = '<table class="table-location"><tbody>';
content += '<tr><th class="table-header">';
content += '<center>Images</center></th></tr>';
var tempSiteNumber = features[0].attributes.SITE_NUMBER;
content += '<tr>';
content += '<tr><th class="table-header">';
content += '<center>' + features[0].attributes.RPUID_NAME + '</center></th></tr>';
for (var i = 0; i < features.length; i++) {
site_number = features[i].attributes.SITE_NUMBER
sitename = features[i].attributes.RPUID_NAME;
cameraPostion = features[i].attributes.CAMERA_POSITION;
imgURL = features[i].attributes.IMAGE_URL;
if (tempSiteNumber != site_number)
{
//then create a new row
tempSiteNumber = site_number;
content += '</tr>';
content += '<tr>';
content += '<tr><th class="table-header">';
content += '<center>'+sitename+'</center></th></tr>';
}
//otherwise everythind goes side to side
content += '<td>' + cameraPostion;
content += '<div><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +' class="imgRWIS" height="125" width="250"></center></div></td>';
}
content += '</tbody></table>';
document.write(content)
return content;
}
window.onload = createLocationTable();
body {
font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
.table-header {
background: #D07D0E;
}
.table-location {
/* background: #dddddd; */
width: auto;
margin: 10px 0;
font-size: 14px;
border: 1px solid black;
}
.table-location td {
padding: 5px;
}
img.imgRWIS {
background: black;
position: relative;
padding: 1px;
display: block;
margin: 0 auto;
}
<!doctype HTML>
<html>
<head>
<script src="test.js"></script>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
</body>
</html>
All you had to do is manage different "names", skip a line when it's different, otherwise all goes on the same line
EDIT
In order to have title over images you have to use a display block container like a Div.
There you go, all problems fixed.
The issue is your <tr> tag.
content += '<tr><td><b>' + sitename + '</b> - ' + cameraPostion + '</td>';
content += '<td><a href =' + imgURL + ' target="_blank"><center><img src=' + imgURL +' class="imgRWIS" height="125" width="200"></center></td></tr>';
The content inside <tr> and </tr> makes for one row.
The content inside <td> and </td> makes for one column.

adjusting the TD content padding using indent button is not working properly

hi i have a table which is editable .i want change my table exactly like a excel page .i have two button left and right that are my indent button for adjusting the Td content padding
my requirement is
1.the first row TD always bold
2.and the second row TD will move 20px when it select and click the left button with normal font weight
3.similar way next row TD are move 20 on first click 40 on second click with small font size
$(function () {
$("tr").on("click", function () {
$(this).toggleClass('selected1');
});
$("td.cat").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing1")
$(this).html("<input id='value' type='text' value='" + OriginalContent + "' />");
})
$("tr").on("click", function () {
$(this).toggleClass('selected1');
});
$(".cat").on("click", function () {
$(this).toggleClass('selected');
});
$("#key").click(function () {
var sl = parseInt($(".selected").css("padding-left"));
sl = sl >= 100 ? "100" : "+=20";
$(".selected").css({
"padding-left": sl
});
$(".cat.selected").each(function () {
var prevTd = $(this).closest('tr').prev('tr').find('td:eq(' + $(this).index() + ')');
console.log('Current td index: ' + $(this).index());
console.log('Previous td content: ' + prevTd.text());
var paddingLeftpl = parseInt($(this).css("padding-left"));
var isPaddingLeft20 = "", isPaddingLeft40 = '';
if (paddingLeftpl > 20)
isPaddingLeft20 = paddingLeftpl;
if (paddingLeftpl > 40)
isPaddingLeft40 = paddingLeftpl;
if (isPaddingLeft20) {
prevTd.addClass("mainfunctionstyle");
prevTd.find('input').addClass("mainfunctionstyle");
prevTd.addClass("mainfunctionstyle")
}
if (isPaddingLeft40) {
prevTd.find('input').addClass("sunfunctionstyle");
prevTd.addClass("subfunctionstyle");
prevTd.addClass("subfunctionstyle");
}
else $(this).css("color", "grey");
});
});
$("#key1").click(function () {
var sl = parseInt($(".selected").css("padding-left"));
sl = sl >= 100 ? "100" : "+=20";
$(".selected").css({
"padding-left": sl
});
$(".cat.selected").each(function () {
var prevTd = $(this).closest('tr').prev('tr').find('td:eq(' + $(this).index() + ')');
console.log('Current td index: ' + $(this).index());
console.log('Previous td content: ' + prevTd.text());
var paddingLeftpl = parseInt($(this).css("padding-left"));
var isPaddingLeft20 = "", isPaddingLeft40 = '';
if (paddingLeftpl > 20)
isPaddingLeft20 = paddingLeftpl;
if (paddingLeftpl > 40)
isPaddingLeft40 = paddingLeftpl;
if (isPaddingLeft20) {
prevTd.addClass("mainfunctionstyle");
prevTd.find('input').addClass("mainfunctionstyle");
prevTd.addClass("mainfunctionstyle")
}
if (isPaddingLeft40) {
prevTd.find('input').addClass("sunfunctionstyle");
prevTd.addClass("subfunctionstyle");
prevTd.addClass("subfunctionstyle");
}
else prevTd.css("color", "grey");
});
});
});
.selected {
background-color: lightblue;
}
.editableTable {
position: static;
width: 100%;
border-collapse: collapse;
}
.editableTable td {
border: 1px solid;
height: 17px;
}
.editableTable .cellEditing1 input[type=text] {
width: 100%;
border: none;
text-align: left;
background-color: transparent;
}
.editableTable .cellEditing1 {
padding: 0;
height: 1px;
}
.mainfunctionstyle {
color: yellow;
font-weight: bold;
font-size: 10px;
}
.sunfunctionstyle {
color: black;
font-weight: normal;
font-size: 8px;
}
.taskstyle {
color: red;
font-weight: normal;
font-size: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="key">left</button>
<button id="key1">right</button>
<table class="editableTable">
<tr>
<td class="cat">rose11</td>
<td class="cat">red12</td>
</tr>
<tr>
<td class="cat">rose21</td>
<td class="cat">red22</td>
</tr>
<tr>
<td class="cat">rose31</td>
<td class="cat">red32</td>
</tr>
<tr>
<td class="cat">rose41</td>
<td class="cat">red42</td>
</tr>
</table>
4.next is become 20 ,40,60px with gray color
this is my code i also share a image for under stand the requirement i want exactly like that image
Added a few lines in jquery.
$(function () {
$("tr").on("click", function () {
$(this).toggleClass('selected1');
});
$("td.cat").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing1")
$(this).html("<input id='value' type='text' value='" + OriginalContent + "' />");
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
//alert('Row: ' + row + ', Column: ' + col);
var pad_left_val = (row+1)*10 + "px";
$(this).css("padding-left", pad_left_val);
})
$("tr").on("click", function () {
$(this).toggleClass('selected1');
});
$(".cat").on("click", function () {
$(this).toggleClass('selected');
});
$("#key").click(function () {
var sl = parseInt($(".selected").css("padding-left"));
sl = sl >= 100 ? "100" : "+=20";
$(".selected").css({
"padding-left": sl
});
$(".cat.selected").each(function () {
var prevTd = $(this).closest('tr').prev('tr').find('td:eq(' + $(this).index() + ')');
console.log('Current td index: ' + $(this).index());
console.log('Previous td content: ' + prevTd.text());
var paddingLeftpl = parseInt($(this).css("padding-left"));
var isPaddingLeft20 = "", isPaddingLeft40 = '';
if (paddingLeftpl > 20)
isPaddingLeft20 = paddingLeftpl;
if (paddingLeftpl > 40)
isPaddingLeft40 = paddingLeftpl;
if (isPaddingLeft20) {
prevTd.addClass("mainfunctionstyle");
prevTd.find('input').addClass("mainfunctionstyle");
prevTd.addClass("mainfunctionstyle")
}
if (isPaddingLeft40) {
prevTd.find('input').addClass("sunfunctionstyle");
prevTd.addClass("subfunctionstyle");
prevTd.addClass("subfunctionstyle");
}
else $(this).css("color", "grey");
});
});
$("#key1").click(function () {
var sl = parseInt($(".selected").css("padding-left"));
sl = sl >= 100 ? "100" : "+=20";
$(".selected").css({
"padding-left": sl
});
$(".cat.selected").each(function () {
var prevTd = $(this).closest('tr').prev('tr').find('td:eq(' + $(this).index() + ')');
console.log('Current td index: ' + $(this).index());
console.log('Previous td content: ' + prevTd.text());
var paddingLeftpl = parseInt($(this).css("padding-left"));
var isPaddingLeft20 = "", isPaddingLeft40 = '';
if (paddingLeftpl > 20)
isPaddingLeft20 = paddingLeftpl;
if (paddingLeftpl > 40)
isPaddingLeft40 = paddingLeftpl;
if (isPaddingLeft20) {
prevTd.addClass("mainfunctionstyle");
prevTd.find('input').addClass("mainfunctionstyle");
prevTd.addClass("mainfunctionstyle")
}
if (isPaddingLeft40) {
prevTd.find('input').addClass("sunfunctionstyle");
prevTd.addClass("subfunctionstyle");
prevTd.addClass("subfunctionstyle");
}
else prevTd.css("color", "grey");
});
});
});
Hope this helps...

getJSON JSON Array - Search Functionality Crashing Client

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

Categories

Resources