Trouble with script-generated dynamic html element - javascript

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.

Related

Error binding Click Event in for loop in Javascript

I am trying to get array elements(which may be objects) in alert onclick. But, message is not binding on click.
this.openLink() method not getting alert for message and correct value.
I am missing something here while binding click events?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myBox(){
this.create = (id, id3 , arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3 , arrData)
}
this.createList = (id, id3 , arrData) =>{
var html = '';
html +='<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
// ---> here, some error for binding click event on li
arrData.forEach((element) => {
$(document).on('click', '#' + iD, () => {
this.openLink(element);
});
});
}
this.openLink = (message) =>{
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
}
</script>
<script>
function abc(){
var arrData = ['a','b','c'];
var arrData2 = ['as','bqsq','csqs'];
var bx = new myBox();
bx.create('arrData',"#box1" , arrData);
bx.create('arrData2',"#box2" , arrData2);
}
</script>
</head>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
</html>
You are assembling the id, in the for loop above your foreach, then you are using that id to set the clicklistener, you need to assemble the correct id at every loop in the foreach or else you will only put a listener on the last button.
Change your forEach to this:
arrData.forEach((element, index) => {
var clickId = id + '_utt' + index;
$(document).on('click', '#' + clickId, () => {
this.openLink(element);
});
});
To put it into the html as an onclick="function()" you need to assign it in the first loop when you are creating the HTML. and move openlink outside myBox()
function myBox() {
this.create = (id, id3, arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3, arrData)
}
this.createList = (id, id3, arrData) => {
var html = '';
html += '<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li ' + 'onclick="openLink(\'' + arrData[i] + '\')" id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
}
}
openLink = (message) => {
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
function abc() {
var arrData = ['a', 'b', 'c'];
var arrData2 = ['as', 'bqsq', 'csqs'];
var bx = new myBox();
bx.create('arrData', "#box1", arrData);
bx.create('arrData2', "#box2", arrData2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
' + 'onclick="openLink(\'' + arrData[i] + '\')" . How does this worked. Can you please explain or provide some link so that I can understand
The line renders as onclick="openLink('a')" onclick="openLink( renders to the DOM as written. the \' renders a ' in the DOM and javascript sees it as a character that way i dont break the string, but it renders as a ' in the DOM. Then i add arrData[i] that is the n'th (or i'th) index in the array. then i use the same trick to close the onclick function off.

Jquery Toggle Content between two specific words in HTML

I have the following Javascript code to toggle content between -a- & -ea-.
When this runs, I have a "View answer" link in my HTML.
Now, I want to behavior like: between -example- & -endexample- , I should have a "View example" link, between -sample- & -endsample-, I should have a "View Sample" link and so on.
The fiddle https://jsfiddle.net/eoc74009/6/
$(document).ready(funciton(){
initToggleContent();
});
initToggleContent = function(){
var p_content = $(".content").html();
p_content = p_content.replace(new RegExp("-a-","g"),"<div class='hidden toggle-content'>")
p_content = p_content.replace(new RegExp("-ea-","g"),"</div><hr>")
$(".content").html(p_content);
$("<a class='toggle-button'>View Answer</a>").insertBefore(".toggle-content");
$(document).on('click',".toggle-button",function(){
$(this).next(".toggle-content").toggleClass("hidden");
if($(this).html()==="View Answer"){
$(this).html("Hide Answer");
}
else{
$(this).html("View Answer");
}
});
}
You can use this code:
p_content = p_content.replace(/-([^\-]+)-([\s\S]*)-end\1-/gm, function(_, name, content) {
return '<a class="toggle-button" data-name="' + name +
'">View ' + name + '</a>' +
'<span class="hidden toggle-content">' +
content + '</span><hr>';
});
span instead of div because div can't be inside p tag.
Regex explanation:
-([^\-]+)- will match dash, any number of not dashes and a dash
([\s\S]*) will match anything including newline characters
-end\1- will match dash end and prevouisly matched name
parentesis are used as capturing group so you can reference them in replace.
And modifed click handler:
$(document).on('click',".toggle-button",function(){
$(this).next(".toggle-content").toggleClass("hidden");
var name = $(this).data('name');
if($(this).html()==="View " + name){
$(this).html("Hide " + name);
}
else{
$(this).html("View " + name);
}
});
JSFIDDLE
I went a little silly on this and kept iterating an the answer to come up with a more frameworky solution, this allows you to create your own html snippets that look kind of like jsx, and rely's on css checkboxes to toggle the content rather than binding js which can get cumbersome if not managed properly.
https://jsfiddle.net/eoc74009/9/
var
$content = $('.content'),
__id = makeNumberIterator(),
text = $content.html();
// this object holds the bbcode functions
var codes = {
sample: bbcode('sample', function(content, id) {
return (
'<section class="sample">' +
'<input type="checkbox" class="sample-checkbox" id="sample-' + id + '">' +
'<label for="sample-' + id + '" class="sample__label">Sample</label>' +
'<div class="sample__content"><h3>' + content + '</h3></div>' +
'</section>'
);
}),
link: bbcode('a', function(content, id) {
return (
'<section class="toggle">' +
'<input type="checkbox" class="toggle__checkbox" id="toggle-' + id + '">' +
'<label for="toggle-' + id + '" class="toggle__label">Answer</label>' +
'<div class="toggle__content">' + content + '</div>' +
'</section>'
)
})
}
$content.html(replaceWithCodes(text, codes));
/**
* replaceWithCodes
*
* this funtion will call each of the bbcodes functions to replace the content
*
* #param {string} content html content from the page
* #param {Object} codes object of the bbcode functions
*/
function replaceWithCodes(content, codes) {
for (var key in codes) {
content = codes[key](content);
}
return content;
}
/**
* bbcode
*
* this is a factory for a function to replace your -bbcode- with a template
*
* #param {string} code bbcode to find in text without hyphens
* #param {Function} template jsx style function template, recieves content and id
*
* #returns {string} replaced template
*/
function bbcode(code, template) {
return function(input) {
var reg = new RegExp('-' + code + '-([^-]+)-end' + code + '-', 'gm');
return input.replace(reg, function(_, content) {
return template(content, __id());
});
}
}
/**
* makeNumeberIterator
*
* this is a helper function to get a function which returns
* an incrementing number
*
* #param {Number} initial initial value to iterate from
*/
function makeNumberIterator(initial) {
var ii = initial || 0;
return function() {
return ii++;
}
}
* {
box-sizing: border-box;
}
.sample,
.toggle {
margin: 1em 0;
}
input[type=checkbox] {
-webkit-appearance: none;
appearance: none;
}
input[type=checkbox] ~ label {
background: #3cf;
color: white;
padding: .3em 1em;
margin: 1em 0;
}
input[type=checkbox] ~ label:before {
content: "View ";
}
input[type=checkbox] ~ .toggle__content,
input[type=checkbox] ~ .sample__content {
display: none;
padding: 1em;
.3em;
}
input[type=checkbox]:checked ~ label:before {
content: "Hide ";
}
input[type=checkbox]:checked ~ .toggle__content,
input[type=checkbox]:checked ~ .sample__content {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<h2>
Hello my name is bleh!
</h2>
<p>
-a- Happy new year man! How ya doing?! -enda- -sample- something something darkside -endsample-
</p>
</div>

Moving Javascript variables into Html Table

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>

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
});

Show Page Loading Spinner in Google Ajax

I have the following code and I would like to know where to place the code to show the Spinner image every time a Dynamic Post is clicked or when you navigate back to the main List Page:
function initialize() {
var feed = new google.feeds.Feed("http://howtodeployit.com/category/daily-devotion/feed/");
feed.setNumEntries(8);
feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
var posts = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
posts += '<li>';
posts += '<a href="#articlepost" onclick="showPost(' + id + ')">';
posts += '<div class="ui-li-heading">' + entry.title + '</div>' ;
posts += '<div class="ui-li-desc">' + n_date + '</div>';
posts += '</a>';
posts += '</li>';
}
posts += '</ul>';
// Append each list of posts to #devotionlist in html page
$("#devotionlist").append(posts);
//$("#devotionlist").listview('refresh');
}
});
}
google.setOnLoadCallback(initialize);
I have tried some codes seen but none works for me...
OK I did figure this out the simplest way. I added the following code in the Function that calls and displays each clicked Posts:
function showPost(id) {
$('#articlecontent').html('<div id="ui_loader"><img src="css/images/ajax-loader.gif" class="ajax_loader"/></div>');
$.getJSON('http://howtodeployit.com/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var output='';
output += '<h3>' + data.post.title + '</h3>';
output += data.post.content;
$('#articlecontent').html(output);
with the following CSS:
#ui_loader {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:1000;
}
.ajax_loader {
position: absolute;
left: 50%;
top: 50%;
margin-left: -32px; /* -1 * image width / 2 */
margin-top: -32px; /* -1 * image height / 2 */
display: block;
}
Note: I took out the opacity from the CSS since the Loader was looking too dark and too white when I increase or decrease the opacity settings, so what I did was to generate a new Loader with transparent background from AJAX Loader Site

Categories

Resources