I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')
Related
I'm trying to use the onclick='shell.openItem('filename') with the filename being populated by JSON. When I console.log(data[i].url) it returns the correct kmz file for each button, but when I click on the button it says Uncaught Reference Error: filename.kmz is not defined.
Thoughts on what I'm missing? Thanks.
var portsbtn = document.getElementById("portsbtn");
portsbtn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'jsonclean.json');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData[23]);
};
ourRequest.send();
});
//WRITE HTML FROM JSON ON BUTTON CLICK
function renderHTML(data) {
var htmlString = "";
$('#aceCategory').empty();
for (i = 0; i < data.length; i++) {
htmlString += "<p class='categoryName'>" + data[i].category + "</p>" + "<tr>" + "<td class='feedDesc'>" + "<b>" + data[i].name +
"</b>" + "<br>" + data[i].desc + "</br>" + "<br>" + "<input type='button' id='openBtn' style='border-radius: 25px; outline: none' value='Open Link' onclick='shell.openItem(" + data[i].url + ");'" + ">" + "</td>" +
"</tr>"
console.log(data[i].url)
};
aceFeedTable.insertAdjacentHTML('beforeend', htmlString)
}
I figured it out. Code below.
htmlString += "<p class='categoryName'>" + data[i].category + "</p>" + "<tr>" + "<td class='feedDesc'>" + "<b>" + data[i].name +
"</b>" + "<br>" + data[i].desc + "</br>" + "<br>" + "<input type='button' id='openBtn' style='border-radius: 25px; outline: none' value='Open Link' onClick='openWindow(\"" + data[i].url + "\" )' >" + "</td>" +
"</tr>"
};
aceFeedTable.insertAdjacentHTML('beforeend', htmlString)
}
function openWindow(url) {
shell.openItem(url);
console.log(url);
}
I try make a poll, basically I refresh my petition every 3s to the API using jsonp and getJSON the problem is my view also refresh at the same time and blink in the interface of the client (HTML), I have some like this
var chatbox = $("#chatbox");
singleChatView();
setInterval(function () {
chatbox.empty();
singleChatView();
}, 1000);
function singleChatView() {
var chatid = localStorage.getItem('chatid');
$.getJSON("http://myapi/?chatid=" + chatid + "&jsonp=?", function (chats) {
console.log(chats);
$.each(chats.DATA, function (key, c) {
$('.msgRecipientName').text(c.SENTBY.name);
if (c.SENTBY.id == userInfo.PROFILE.USERID) {
chatbox.append(
"<li class='msgThread group currentUser'>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgDate'>" +
formatDate(c.CREATEDON) +
"</div>" +
"</li>"
);
} else {
chatbox.append(
"<li class='msgThread group'>" +
"<div class='msgAuthor' style='background: #fff url(myapi/100_couple.png) 50% background-size: cover;'>" +
"<a ng-href=''>" +
"<span></span>" +
"</a>" +
"</div>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
}
});
});
}
I don't have any idea how I can do this and void this issue with the view, can some one help me, all this is new for me thanks
I would suggest trying the following. The blink is most likely due to you clearing the chatbox and not putting anything in there until the ajax returns. This version, aside from reducing the number of times the DOM is changed, also doesn't replace the chatbox until it has built all the html that should be in it.
var chatbox = $("#chatbox");
//start the chat loop
singleChatView();
function singleChatView() {
var chatid = localStorage.getItem('chatid');
$.getJSON("http://myapi/?chatid=" + chatid + "&jsonp=?", function(chats) {
console.log(chats);
//collect the messages
//if we update the page once, the browser has to do less work rendering
//all the changes
var messages = [];
//keep track of the "c.SENTBY.name"
//since you are doing a global selector and setter, the value will
//end up being the last value you update all them to be anyway
//no need to update multiple times
var sendby = '';
$.each(chats.DATA, function(key, c) {
sentby = c.SENTBY.name;
if (c.SENTBY.id == userInfo.PROFILE.USERID) {
messages.push(
"<li class='msgThread group currentUser'>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
} else {
messages.push(
"<li class='msgThread group'>" +
"<div class='msgAuthor' style='background: #fff url(myapi/100_couple.png) 50% background-size: cover;'>" +
"<a ng-href=''>" +
"<span></span>" +
"</a>" +
"</div>" +
"<div class='msgBalloon group'>" +
"<div class='msgHeader'>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgFull'>" + c.MESSAGE + "</div>" +
"</div>" +
"</div>" +
"<div class='msgFrom'>" + c.SENTBY.name + "</div>" +
"<div class='msgDate'>" + formatDate(c.CREATEDON) + "</div>" +
"</li>"
);
}
});
//update the recipent with the last sent by, once
$('.msgRecipientName').text(sentby);
//replace all the chatbox text with the collected html that would have
//otherwise been append one at a time
chatbox.html(messages);
//now that we've finished this iteration, start the next iteration after
//a second
setTimeout(singleChatView, 1000);
});
}
I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});
I'm trying to nest 3 divs within a "row" div.
I had this working in "long format" (multiple var's instead of looping through the array). I've refactored my code and now I don't get any error codes AND my code does not append to the HTML file. When I console log I get an array with 3 objects. I'm sure i'm missing something minor.
Anyways some help would be great!
<div class="row">
**nested divs go here.
</div>
$(document).ready(function() {
$.get("http://api.openweathermap.org/data/2.5/forecast/daily?id4726206&cnt=3", {
APPID: "MY API KEY",
lat: 29.423017,
lon: -98.48527,
units: "imperial"
}).done(function(data) {
var stationId = data.city.name;
// Stattion Name
$('#station').append(stationId);
//console.log(data);
var forecast = data.list;
//Wind Direction in Compass Format
function getDirection(dir) {
var compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW'];
var result = Math.floor((360 - dir) / 22.5);
return compass[result];
}
//Forecast Variables
$.each(forecast, function(i, v) {
var html = '';
html += "<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>";
html += "<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°';
html += " / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>";
html += "<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon;
html += ".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main;
html += "</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>";
html += "<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>";
html += "<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed));
html += " mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>";
html += "<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div>";
return html;
});
$('.forecast').append(forecast);
console.log(forecast);
});
});
You are trying to append the array forecast in html. which wont work. You should declare the html variable outside and then use it in append function.
I will also recommend to use string builder logic using array and then convert it to string and append it. remember string concatenation is heavy operator as it creates new instance of elememt every time concatenation is done :
var html = [];
$.each(forecast, function(i, v) {
html.push("<div class='col-sm-3 wInfo'>" + "<div class='title'>High / Low</div>");
html.push("<div class='cTemp'>" + (Math.ceil(forecast[i].temp.max)) + '°');
html.push(" / " + (Math.ceil(forecast[i].temp.min)) + '°' + "</div>");
html.push("<div class='tempIcon'>" + "<img src='http://openweathermap.org/img/w/" + forecast[i].weather[0].icon);
html.push(".png' alt=''></div>" + "<div class='conditions' id='castId'>" + '<span class="cond">' + forecast[i].weather[0].main);
html.push("</span>: " + "<span>" + forecast[i].weather[0].description + '</span>' + "</div>");
html.push("<div class='conditions'>" + "<span class='cond'>Humidity: </span>" + "<span>" + forecast[i].humidity + "%</span></div>");
html.push("<div class='conditions'>" + "<span class='cond'>Wind: </span>" + "<span>" + (Math.floor(forecast[i].speed)));
html.push(" mph / " + getDirection(forecast[i].deg) + "</span></div>" + "<div class='conditions'>");
html.push("<span class='cond'>Pressure: </span>" + "<span>" + forecast[i].pressure + "</span></div></div>");
});
$('.forecast').append(html.join(""));
Fiddle
I want to put the names of all record in my array into a table my array isn't index correctly so i used $.each instead of iterating over the using for loop. My problem is I only get to show the last element but if i try to show a value that is existing to both the array it is showing correctly.
What am i missing in this code.
Any idea is appreciated
This is my javascript
for (var i = 0; i < name.length; i++) {
var names = name[i].Names;
$.each(names, function (item, names) {
tr = $('<tr class=""/>');
//console.log(complainant[obj]);
//var names = complainant[obj];
//if(names.hasOwnProperty('fname')){
console.log(names.suffix);
var acronymc;
var upper = names.mname.toUpperCase();
if (upper) {
var matches = upper.match(/\b(\w)/g);
//var matches = upper.replace(/^(\S+)\s+(\S).*/, '$1 $2.');
//acronym = upper.slice(0,1);
var acronym1 = matches.join('');
acronymc = acronym1.slice(-1);
} else {
acronymc = '';
}
tr.append("<td id=''>" + "<span id='fname'>" + names.fname + "</span>" + " " + "<span id='mname'>" + acronymc + "</span>" + " " + "<span id='lname'>" + names.lname + "</span>" + " " + "<span id='suffix'>" + names.suffix + "</span>" + "</td>");
tr.append("<td id=''>" + '<span id="street">' + names.street + '</span>' + " " + '<span id="brgy">' + names.brgy + '</span>' + " " + '<span id="town">' + names.town + '</span>' + " " + '<span id="city">' + names.city + '</span>' + "</td>");
tr.append("<td id=''>" + names.contactnum + "</td>");
tr.append("<td id=''>" + "<a href='#' class='editcomplainant'>Edit</a>" + "/" + "<a href='#' class='delete'>Delete</a>" + "</td>");
//}
});
$("#nameslist").append(tr);
}
Put the $('#nameslist').append(tr); call inside the $.each block.
Here is a way of improving the creation of tds:
var html =
"<td>" +
"<span id='fname'/> " +
"<span id='mname'/> " +
"<span id='lname'/> " +
"<span id='suffix'/>" +
"</td>";
var td = $(html);
td.find('#fname').text(names.fname);
td.find('#mname').text(acronymc);
td.find('#lname').text(names.lname);
td.find('#suffix').text(names.suffix);
tr.apppend(td);
Why is this better (imho)?
You will not create unintentional html tags by having < and > inside the variables.
Appropriate escaping (auml codes) will be automatically generated
It is easier to read