IE11 and a Javascript-based Modal Form Acting Funny - javascript

I have a WordPress plugin called Easy Age Verifier in the WordPress repository and got a support request that has me flat-out baffled. Here's his message:
On Explorer 11 on Windows 10, the fields can't be filled in. Clicking in a field seems to activate a blinking text line somewhere way below the fields and typing numbers in does nothing. I can't include a link because the site is in development.
I installed Easy Beer Lister onto my test environment, and whudduya know? I get the same exact problem.
The code that runs this plugin can be seen in the repository, but I'll go ahead and put a copy of the code that creates the form here as well.
Has anyone else experienced this issue? If so, can you point me in the direction on what causes it, and how I can fix it? Thank you!
//For the max value of the input in the age form
taseavCurrDate = new Date();
if(taseavData.debug == true){
var taseavDebugLog = [];
}
function taseavDebug(log){
if(taseavData.debug == true){
console.log(log);
taseavDebugLog.push(log);
}
return
}
//Gets the cookie that was just stored
function taseavGetCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return false;
}
//The actual form
function taseavAgeForm(){
var result;
result = "<div id='taseav-age-verify' class='" + taseavData.wrapperClass + "'>";
result += "<form class='" + taseavData.formClass + "'>";
result += "<h2>" + taseavData.formTitle + "</h2>";
result += "<div class='taseav-month'>";
result += "<label>Month</label>";
result += "<input name='month' type='number' min='1' max='12' required>";
result += "</div>";
result += "<div class='taseav-day'>";
result += "<label>Day</label>";
result += "<input name='day' type='number' min='1' max='31' required>";
result += "</div>";
result += "<div class='taseav-year'>";
result += "<label>Year</label>";
result += "<input name='year' type='number' min='1900' max='"+ taseavCurrDate.getFullYear() +"' required>";
result += "</div>";
result += "<input type='submit' value='submit'>";
result += "</form>";
result += "</div>";
return result;
}
//Stores the age into a cookie
function taseavStoreAge(){
var month = jQuery('#taseav-age-verify input[name="month"]').val();
var day = jQuery('#taseav-age-verify input[name="day"]').val();
var year = jQuery('#taseav-age-verify input[name="year"]').val();
if(month < 10){
month = "0" + month;
}
if(day < 10){
day = "0" + day;
}
var result = "taseavdob=" + year + "-" + month + "-" + day;
document.cookie = result;
taseavDebug('Age stored as a cookie. Value = ' + result);
}
function taseavGetAge() {
taseavDebug('Evaluated Date of Birth: ' +taseavGetCookie('taseavdob'));
var birthday = new Date(taseavGetCookie('taseavdob'));
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
function taseavIsAboveAge(ageToCheck){
if(!ageToCheck){
taseavDebug('Getting minimum age to check...')
ageToCheck = taseavData.minAge;
taseavDebug('Age to check: ' + taseavData.minAge);
};
taseavDebug('Getting evaluated age to check against...')
var age = taseavGetAge();
taseavDebug('Age checked: ' + age);
if(age < ageToCheck){
return false;
}
else{
return true;
}
}
function confirmAge(){
if(taseavIsAboveAge() == false){
taseavDebug('User is underage. Displaying message "' + taseavData.underageMessage + '"');
alert(taseavData.underageMessage);
if(taseavData.debug == true){
alert(taseavDebugLog.join('\n \n'));
}
history.back();
}
else{
taseavDebug('User is older than the min age of ' + taseavData.minAge +'. Removing age verify overlay.');
jQuery('#taseav-age-verify').remove();
}
}
jQuery(document).ready(function(){
jQuery("html").append(taseavAgeForm());
jQuery("#taseav-age-verify form").submit(function(e) {
e.preventDefault();
});
//Disables mouse-wheel when gallery is open
jQuery("#taseav-age-verify").bind("mousewheel", function() {
return false;
});
jQuery('#taseav-age-verify').submit(function(){
taseavStoreAge();
confirmAge();
taseavDebug(taseavData);
});
})
.taseav-age-verify {
width: 100%;
height: 100%;
position: fixed;
background: rgba(0,0,0,0.9);
top: 0;
left: 0;
z-index:9999;
}
.taseav-age-verify form {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
max-width:600px;
width:90%;
}
.taseav-age-verify input{
width:calc(100% - 24px);
padding:10px;
border-radius:5px;
}
.taseav-age-verify div{
margin-bottom:20px;
max-width:100%;
float:left;
}
.taseav-age-verify .taseav-month{
width:24%;
}
.taseav-age-verify .taseav-day{
width:24%;
}
.taseav-age-verify .taseav-year{
width:50%;
}
.taseav-age-verify div:nth-of-type(2){
margin-left:1%;
margin-right:1%;
}
.taseav-age-verify input[type="submit"]{
clear:both;
width:100%;
}
.taseav-age-verify{
color:white;
}
.taseav-age-verify label{
color:white;
}
.taseav-age-verify h2{
font-size:30px;
text-align:center;
color:white;
}

Please either wrap your label around your input, or give the input an id and use the "for" property on your label, where the value is the id of the input.
This will help you with your focus issues and make your form accessible.

Solved. The problem was I appended code after the 'html' tag, instead of the 'body' tag.
Here's what I originally had:
jQuery("html").append(taseavAgeForm());
Here's what I had to change it to:
jQuery("body").append(taseavAgeForm());

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.

Custom CSS in script

I am trying to modify the CSS of this code so that the articles are in columns of 3 articles side by side.
The CSS / script shows the articles one below the other, I would like to show them side by side.
Example:
1 - 2 - 3
4 - 5 - 6
Even though I have already made some modifications, the result I want is not showing up.
Does anyone know where the error code is?
<style>
/**
* Blogger Archive with Pagination - Default Theme
* Visit: http://www.dte.web.id
*/
#toc-outer {
font:normal 11px/14px Arial,Sans-Serif;
color:#666;
text-align:left;
margin:0px auto;
padding:15px;
background-color:white;
-webkit-box-shadow:0px 1px 4px rgba(0,0,0,0.6);
-moz-box-shadow:0px 1px 4px rgba(0,0,0,0.6);
box-shadow:0px 1px 4px rgba(0,0,0,0.6);
}
#loadingscript {
background:#F6EFBB url('data:image/gif;base64,R0lGODlhEAAQAPUAAP///wAAAO7u7lRUVAAAALa2tvb29tbW1uLi4mZmZggICL6+vk5OTtzc3BwcHCgoKOjo6GxsbCIiIkZGRpiYmH5+fsrKyoyMjKqqqvz8/NDQ0IaGhmBgYBYWFnJycsTExFpaWpKSkqSkpEBAQC4uLjQ0NJ6ennh4eA4ODjo6OrCwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAGo0CA0IDJAAhIR0YgbDYmhAKggyQIDp/mwYGcADzIEGDT0QgRjyrgQHAYIMiRgAmhII0EDGBUFQ0SCAAGD0YNAiJIAwtHSBUQGQZNCEZNVQQSTZkWEQpIChEWQpQAApYEmRkLgQAZGRpQSAALA0kQTQlCBSQlBZahDEIECotvBgxIwL1ZVYBCBxIEGgadIAAcSB0NWhdjahoEI9qZttexABiRQkEAIfkECQoAAAAsAAAAABAAEAAABmBAgBAgGhGEhJFoyGQQnsjniCk0PY+Aq4eZQACs2OfWcCI+vVbkWEEoXtHCtfR6ZhrYV6p+z9fTCVtDYFdGYgAGQmiEIoZ3SIptACNyUWgMdnhRBF5UJ3lZTwl7bkhKTEEAIfkECQoAAAAsAAAAABAAEAAABp1AgBAAGRGOQoxhKNRoAI8jAaAhjA7DQwcEWBy5HOnSwDh+MuUPQEp4FqQowGFqOA6ez8XgeMogAAgoZwAbXEN+TA0GKg5SChEWTEMgbJUFkgAWCQpsHRhMAggZTEYboxdDBkYEAwsABU8QKQSjIwACbCIZGRVScgSoF0cjAgAZHUcTAB5HAgIOHU9CEBMEl8gECRkf0qkYo1IMEExBADsAAAAAAAAAAAA=') no-repeat 50% 46%;
padding:10px;
font:bold 20px Georgia,Serif;
color:black;
height:400px;
text-indent:-9999px;
-webkit-box-shadow:inset 0px 0px 0px 5px #EAE0AD;
-moz-box-shadow:inset 0px 0px 0px 5px #EAE0AD;
box-shadow:inset 0px 0px 0px 5px #EAE0AD;
}
.itemposts {
margin:0px auto 5px;
height:auto;
background-color:white;
overflow:hidden;
display:block;
}
.itemposts h6 {
margin:0px auto 2px;
font:bold 12px/14px Arial,Sans-Serif;
background-color:#9BB009;
background-image:-webkit-linear-gradient(#9BB009, #AABD30);
background-image:-moz-linear-gradient(#9BB009, #AABD30);
background-image:-ms-linear-gradient(#9BB009, #AABD30);
background-image:-o-linear-gradient(#9BB009, #AABD30);
background-image:linear-gradient(#9BB009, #AABD30);
padding:10px 15px;
text-transform:none;
color:white;
}
.itemposts h6 a {
color:white;
text-decoration:none;
text-shadow:0px 1px 0px rgba(0,0,0,0.3);
}
.itemposts img {
float:left;
height:72px;
width:72px;
margin:2px 10px 2px 0px;
-webkit-box-shadow:none;
-moz-box-shadow:none;
box-shadow:none;
background-color:#fafafa;
border:1px solid #dcdcdc;
padding:4px;
}
.itemposts .iteminside {
padding:10px;
background-color:#f2f2f2;
background-image:-webkit-linear-gradient(#f2f2f2, white);
background-image:-moz-linear-gradient(#f2f2f2, white);
background-image:-ms-linear-gradient(#f2f2f2, white);
background-image:-o-linear-gradient(#f2f2f2, white);
background-image:linear-gradient(#f2f2f2, white);
border-top:1px solid #e5e5e5;
-webkit-box-shadow:inset 0px 1px 0px white;
-moz-box-shadow:inset 0px 1px 0px white;
box-shadow:inset 0px 1px 0px white;
}
.itemposts .itemfoot {
clear:both;
border:1px solid #EAE7DB;
padding:5px 10px;
margin:10px 0px 0px;
background-color:#FAFAE7;
color:#4B86C1;
overflow:hidden;
}
.itemposts .itemfoot a.itemrmore {
font-weight:bold;
color:#895F30;
float:right;
text-decoration:none;
}
.itemposts .itemfoot a.itemrmore:hover {
color:#9BB009;
text-decoration:underline;
}
#itempager {
background-color:#F2F0F1;
padding:30px 0px;
border-top:1px solid #E5E5E5;
-webkit-box-shadow:inset 0px 1px 0px white;
-moz-box-shadow:inset 0px 1px 0px white;
box-shadow:inset 0px 1px 0px white;
}
#pagination, #totalposts {
color:#999;
font:bold 10px Verdana,Arial,Sans-Serif;
padding:0px;
margin-bottom:10px;
text-align:center;
}
#pagination span, #pagination a {
border:1px solid #e5e5e5;
color:white;
display:inline;
margin:0 1px;
padding:2px 5px;
text-indent:0px;
background-color:#8899D0;
text-decoration:none;
}
#pagination span.actual,
#pagination a:hover {
background-color:#7483BC;
}
#pagination span.hidden {
display:none;
}
</style>
Script
<script>
var showPostDate = true,
showComments = true,
idMode = true,
sortByLabel = false,
labelSorter = "Games",
loadingText = "Loading...",
totalPostLabel = "Jumlah posting:",
jumpPageLabel = "Halaman",
commentsLabel = "Komentar",
rmoreText = "Selengkapnya ►",
prevText = "Sebelumnya",
nextText = "Berikutnya",
siteUrl = "https://elfenliedbrazil.blogspot.com/",
postPerPage = 6,
numChars = 370,
imgBlank = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC";
</script>
<script type='text/javascript'>
//<![CDATA[
// -----------------------------------------------------------------------------------------
//
// Original:
// Modified by Taufik Nurrohman
//
// -----------------------------------------------------------------------------------------
var minpage = 6; // Minimum number to display the page
var maxpage = 10; // The maximum number of pages to display
var firstpage = 0; // Detect the first time it is executed
var pagernum = 0; // Contain the page number where we
var postsnum = 0; // Start the first page
var actualpage = 1; // Starting value of the current page (it will change if you click the pagination).
// This is the container template that will be used to insert the posts template, pagination and the posts count
document.write('<div id="toc-outer"><div id="results"></div><div id="itempager" style="position:relative;"><div id="pagination"></div><div id="totalposts"></div><a title="Taufik Nurrohman" style="display:block!important;visibility:visible!important;opacity:1!important;position:absolute;bottom:10px;right:14px;font:normal bold 8px Arial,Sans-Serif!important;color:#666;text-shadow:0 1px 0 rgba(255,255,255,.1);text-decoration:none;" href="http://hompimpaalaihumgambreng.blogspot.com/2012/03/daftar-isi-blogger-dengan-navigasi.html" target="_blank">►TN</a></div></div>');
var _results = document.getElementById('results');
var _pagination = document.getElementById('pagination');
var _totalposts = document.getElementById('totalposts');
// Build the table of contents framework
function showPagePosts(json) {
var entry, posttitle, posturl, postimg, postsumm, replies, monthnames, timepub, output = "";
if (pagernum === 0) {
postsnum = parseInt(json.feed.openSearch$totalResults.$t);
pagernum = parseInt(postsnum / postPerPage) + 1;
}
for (var i = 0; i < postPerPage; i++) {
if ("entry" in json.feed) {
if (i == json.feed.entry.length) break;
entry = json.feed.entry[i];
posttitle = entry.title.$t; // Get the post title
// Get rel="alternate" for truly post url
for (var k = 0, elen = entry.link.length; k < elen; k++) {
if (entry.link[k].rel == "alternate") {
posturl = entry.link[k].href; // This is your real post URL!
break;
}
}
// Get the comments count
for (var l = 0, clen = entry.link.length; l < clen; l++) {
if (entry.link[l].rel == "replies" && entry.link[l].type == "text/html") {
var commentsnum = entry.link[l].title.split(" ")[0]; // This is your comments count
break;
}
}
// If the Blogger-feed is set to SHORT, then the content is in the summary-field
postsumm = ("summary" in entry) ? entry.summary.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : ""; // Get the post summary
// Reduce post summaries to "numChars" characters.
// "numChars" is a variable. You determine the value
if (postsumm.length > numChars) {
postsumm = (numChars > 0 && numChars !== false) ? postsumm.substring(0, numChars) + '...' : "";
}
// Get the post date (e.g: 2012-02-07T12:56:00.000+07:00)
var _postdate = entry.published.$t,
_cdyear = _postdate.substring(0, 4), // Take 4 characters from the "postdate" beginning, it means the year (2012)
_cdmonth = _postdate.substring(5, 7), // Take 2 character 5 step from "postdate" beginning, it mean the month (02)
_cdday = _postdate.substring(8, 10); // Take 2 character 8 step from "postdate" beginning. it means the day (07)
// Month array template
monthnames = (idMode) ? ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"] : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The final product of the post date = (07 Feb 2012) (cdday monthnames cdyear)
timepub = (showPostDate) ? _cdday + ' ' + monthnames[parseInt(_cdmonth, 10) - 1] + ' ' + _cdyear + ' - ' : '';
// The final product of the comments count & comments label (10 Komentar) (commentsnum commentsLabel)
replies = (showComments) ? commentsnum + ' ' + commentsLabel : '';
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
}
}
// Put the whole template above into <div id="results"></div>
_results.innerHTML = output;
_create_pagination();
}
// Build the pagination
function _create_pagination() {
output = "";
var starter = 0;
output += ((actualpage > 1) ? '<a title="' + prevText + '" class="prevjson" href="javascript:_init_script(' + (actualpage - 1) + ')">' + prevText + '</a>' : '<span class="prevjson hidden">' + prevText + '</span>') + '<em style="font:inherit;color:inherit;" class="pagernumber">';
if (pagernum < (maxpage + 1)) {
for (starter = 1; starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
} else if (pagernum > (maxpage - 1)) {
if (actualpage < minpage) {
for (starter = 1; starter < (maxpage - 2); starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else if (pagernum - (minpage - 1) > actualpage && actualpage > (minpage - 1)) {
output += '1';
output += '2';
output += ' ... ';
for (starter = actualpage - 2; starter <= actualpage + 2; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else {
output += '1';
output += '2';
output += ' ... ';
for (starter = pagernum - (minpage + 1); starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
}
}
output += '</em>' + ((actualpage < starter - 1) ? '<a title="' + nextText + '" class="nextjson" href="javascript:_init_script(' + (actualpage + 1) + ')">' + nextText + '</a>' : '<span class="nextjson hidden">' + nextText + '</span>');
_pagination.innerHTML = output;
_totalposts.innerHTML = totalPostLabel + ' ' + postsnum + ' - ' + jumpPageLabel + ' ' + ((actualpage * postPerPage) - (postPerPage - 1)) + ((actualpage < starter - 1) ? ' - ' + (actualpage * postPerPage) : "");
}
// Functions to remove and append the callback script that has been manipulated in the `start-index` parameter
function _init_script(n) {
var parameter = (n * postPerPage) - (postPerPage - 1), old, s,
head = document.getElementsByTagName('head')[0],
url = (sortByLabel) ? siteUrl + '/feeds/posts/summary/-/' + labelSorter + '?start-index=' + parameter : siteUrl + '/feeds/posts/summary?start-index=' + parameter; // Optional: Sort posts by a specific label
if (firstpage == 1) {
// Jump to top
document.documentElement.scrollTop = _results.offsetTop - 30;
document.body.scrollTop = _results.offsetTop - 30;
// Remove the old callback script
old = document.getElementById("TEMPORAL");
old.parentNode.removeChild(old);
}
_results.innerHTML = '<div id="loadingscript">' + loadingText + '</div>';
_pagination.innerHTML = '';
_totalposts.innerHTML = '';
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&max-results=' + postPerPage + '&orderby=published&alt=json-in-script&callback=showPagePosts';
s.id = 'TEMPORAL';
head.appendChild(s);
firstpage = 1;
actualpage = n;
}
// Execute the _init_script() function with parameter as `1` on page load
// So it will show the first page.
window.onload = function() {
_init_script(1);
};
//]]>
</script>
you can do with css. please apply the css code before closeing style tag
/* here the updated css */
#results {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.itemposts {
width: 33%;
margin-bottom: 10px;
}
/* media query for mobile responsiveness */
#media (max-width:882px) {
.itemposts {
width: calc(50% - 10px);
}
}
#media (max-width:576px) {
.itemposts {
width: 100%;
}
}

How to print the array values in html dom using java script? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have created a bus seat layout dynamically ....
and i have selected seats are pushed to array...
and how to print the array values in html DOM.....
below is my html code
<div>
<h2> Choose seats by clicking the corresponding seat in the layout below:</h2>
<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>
below is my css
#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{
verticle-align:middle;
list-style: none outside none;
padding-left:35px;
height:35px;
float:left;
}
below is my js
$(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(''));
// Add already reserved seats
localStorage.setItem('SeatNum', JSON.stringify(reservedSeat));
};
//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);
var selectedSeat = JSON.parse(localStorage.getItem('SeatNum'));
if($(this).hasClass(settings.selectingSeatCss)){
// Add seat in local storage
selectedSeat.push(parseInt($(this).find('a').text()));
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
else{
// Remove seat from local storage
selectedSeat.splice(selectedSeat.indexOf(parseInt($(this).find('a').text())), 1);
localStorage.setItem('SeatNum', JSON.stringify(selectedSeat));
}
}
// Logging
console.log('Reserved and selecting seats : ' + JSON.parse(localStorage.getItem('SeatNum')));
});
$('#btnShow').click(function myFunction() {
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(','));
})
});
how to print the array values in html DOM....
i put an alert..
i tried code but that does't work..
i created bus seat layout dynamically i am putting an alert to show the selected seats and all seats but i want to print the selected seat in html Dom....
Take a div in the end of your html
and then put that line where you set the alert
$('#showSit').text(JSON.parse(localStorage.getItem('SeatNum')));

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

Categories

Resources