I´m populating webpage with sharepoint so I do a json to get data with ajax like these:
function completeFleet(data, target, eng) {
var items = data.d.results;
console.log(items);
var prefix = "<div class='row'>";
var sufix = "</div>";
var menu = "<div class='col-md-4'>";
var cat = "";
var spec = "";
var counter = 0;
var obj = null;
for (item in items) {
spec = "";
if (counter == 1) {
menu += "</div><div class='col-md-4'>";
counter = 0;
}
if (eng) {
obj = JSON.parse(items[item].Specifications);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
} else {
obj = JSON.parse(items[item].Especificaciones);
for (var key in obj) {
spec += "<div class='row'><div class='col-md-12 ftBottomSeparator'><span class=' t10'>" + key + "</span> <span class='t06' style='float:right;'>" + obj[key] + "</span></div></div>";
}
menu += "<div class='row ftContainerOut'><div class='col-md-12 ftContainer'><div class='row ftHeader'><div class='col-xs-9 t09'>" + items[item].Title + "</div><div class='col-xs-3 text-right'></div></div><div class='row'><div class='col-md-6' style='padding-top:10px'><img src='" + items[item].Imagen.Url + "' class='img-responsive img-center' style='border:0px solid blue; max-width:150px;max-height:120px;' /></div><div class='col-md-6'>" + spec + "</div></div></div></div>";
}
counter++;
}
$(target).html("<div class='panel-body'><div class='container-fluid'>" + prefix + menu + sufix + "</div></div>");
}
I have 5 objects different, but one of these don´t show data, my webpage is in english and spanish, in english it charge all data, but in spanish one of these
doesn´t works and I get error at position 36, and position 36 is the item don´t show. Any idea what is wrong here? Regards
These one works
and this no works
---------Update------------
If I comment this line:
//obj = JSON.parse(items[item].Especificaciones);
and put
if(items[item].Especificaciones){
JSON.parse(items[item].Especificaciones);
}
it now runs with image, but now I don´t have my "Especificaciones" lists
Now when I use
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
I get something like these:
make sure value is not null for the corresponding key inside JSON.parse. For example-
JSON.parse(items[item].Specifications)
make sure items have value in item index and items[item] has the property Specifications.
you can check if items[item].Specifications is not null before JSON.parse.
if(items[item].Specifications){
JSON.parse(items[item].Specifications)
}
Update
JSON.parse() is used to convert a string containing JSON notation into a Javascript object. To be valid JSON, strings must be in double quotes.
Try stringify the object and then parse again.
var stringifyObj = JSON.stringify(items[item].Especificaciones);
var obj = JSON.parse(stringifyObj);
The reason for the error is that JSON.parse() expects a String value and items[item].Especificaciones is an Array
"Eslora":100 pies"
You should probably opening the quotes when you start writing a string value
Related
Let data be a JSON,
what I am trying here is appending multiple elements according to the data from JSON to the div ,
<div class="studentTab" ></div>. How can I achieve this ?
(nb: please consider that we have 2 Languages and 2 Specializations)
for (i = 0; i < 10; i++) {
var html = '<div class="dtls">' +
'' +
'<h4 class="verified">' + data.student[0].firstName + '</h4 >' +
'<ul>' +
'<li>' + data.student[0].location + '</li>' +
'<li>' + data.student[0].mark + ' /hour</li>' +
'<li>' + data.student[0].year+ ' accademic year</li>' +
if (data.student[0].Languages != null)
{
var lang = string.Join(",", data.student[0].Languages.Select(it => it.Name));
<li>lang </li>
}
if (data.student[0].Specializations.length > 1)
{
var rcount = data.student[0][index].Specializations.length - 1;
<li>data.student[0].Specializations[0].Name + rcount more</li>
}
else
{
<li>data.student[0].Specializations[0].Name</li>
}
'</ul>' +
'</div>'
$('#studentTab').append(html);
};
You may use map() for solving such problem. Please make check:
If your 'data' is underfined or not;
Better save your data.student[0] in some variable;
You never know how many objects inside of data you have. Probably some times is underfined due to network errors or more or less objects due to some back-end updates
I have a foreach function which listing all members of array. I want that member of array is a link which change input value.
I have function for reading input like this
<input type="text" id="syote" name="syote" value="" />
<button id="myBtn" onclick="submitti()">Submit</button>
function submitti(){
let current ="syote"
var txt = ""
let array2 = [
'soita',
'sammuta',
'google',
'listaa',
'oskari',
'tee popup',
'10',
'input alas',
'input ylös',
'värillinen',
'mustavalkoinen',
'kysely'
]
if(syote.value.toLowerCase() == "listaaa"){
document.getElementById("vas-col").className = "vasen";
array2.forEach(myFunction);
document.getElementById("result1").innerHTML = txt;
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta()>" + value + "</a>" + "<br>";
}
}
function Muuta(value) {
input.value = "asdasdasd";
}
This is working and it change input value to asdasdasd.
I want it change input value same than member of array list.
I tried these without succes:
function myFunction(value, array2) {
txt = txt + "<a href=# onclick=Muuta(value)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
function myFunction(value, array2) {
txt = txt + "<a href=# title=value onclick=Muuta(this.title)>" + value + "</a>" + "<br>";
function Muuta(value) {
input.value = value;
}
Found some examples also and not working in my case. Like this: javascript change input value by link title
After many hours i find solution for this problem.
With this it works:
if(syote.value.toLowerCase() == "listaa"){
// Näissä kohdissa missä id:ssä on väliviiva täytyy käyttää edessä document.getElementById. Ilman sitä ei muuta classia ja näin ollen scroll ei ilmesty.
document.getElementById("vas-col").className = "vasen scroll";
array.forEach(ListaaKomennot);
result1.innerHTML = txt;
function ListaaKomennot(value, array) {
txt = txt + "<a href='#' title='" + value + "' onclick='MuutaArvo(this.title);'>" + value + "</a>" + "<br>";
}
}
function MuutaArvo(arvo) {
syote.value = arvo;
}
In title is very important to be ' before " and same vice versa after value. Without ' ' it cuts out after whitespace when change value of input to title. If you have only words without whitespace that is not a problem.
It is best to solve yourself, i learned many new things at same time. Inter alia if your html id name is with - tag like i have in oik-col you must use document.getElementById without it, className won't work.
I have a small Issue Tracker which uses a couple of functions to save and fetch issues to localStorage, all of which works fine, using the Chance uid generator to generate ids. However on making a third function to set the status to closed after getting the id which was generated previously. In console I get an error as below.
(function(event){setStatusClosed(fdf7622a-8738-5384-98b6-9ff9c47b2be0)
}) invalid or unexpected token. index.html:1
It's using onclick to run the function via the close button generated in the fetchIssues() function.
The first 2 functions fetchIssues() and saveIssues() have been working as expected with no errors and correctly converting the array to JSON object on push and back to array on retrieve, but when I try the setStatusClosed function I get the error. I also get similar errors when using other uid generator methods so I decided to stick with Chance. I can't seem to find the error and the log just points me to the event as pasted above. The code is below
/*jslint browser:true */
//Fetch submitted issues or the status of localStorage
function fetchIssues() {
"use strict";
var i = 0;
var issues = JSON.parse(localStorage.getItem("issues"));
var issueList = document.querySelector('#issueList');
issueList.innerHTML = " ";
if(issues !== null) {
for(i = 0; i < issues.length; i++) {
var id = issues[i].id,
desc = issues[i].description,
severity = issues[i].severity,
assignedTo = issues[i].assignedTo,
status = issues[i].status;
issueList.innerHTML += "<div class='well'>" +
"<h6>Issue ID: " + id + "</h6>" +
"<p><span class='Label label-info'>" + status + "</span></p>" +
"<h3>" + desc + "</h3>" +
"<p><span class='glyphicon glyphicon-time'></span>" + severity + "</p>" +
"<p><span class='glyphicon glyphicon-user'></span>" + assignedTo + "</p>" +
"<a href='#' onclick='setStatusClosed("+ id +")' class='btn btn-warning'>Close</a>" +
"<a href='#' onclick='deleteIssue(" + id + ")' class='btn btn-danger'>Delete</a>" +
"</div>";
}
console.log(issues);
} else {
issueList.innerHTML = "<h6 class='text-center'>There are no issues at present</h6>";
}
}
//Save a submitted issue
function saveIssue(e) {
"use strict";
var chance = new Chance();
var issueDesc = document.querySelector("#issueDescInput").value,
issueSeverity = document.querySelector("#issueSeverityInput").value,
issueAssignedTo = document.querySelector("#issueAssignedToInput").value,
issueStatus = "Open",
issueId = chance.guid(),
issues = [],
issue = {
id: issueId,
description: issueDesc,
severity: issueSeverity,
assignedTo: issueAssignedTo,
status: issueStatus
};
//Check if entry already there
if(localStorage.getItem("issues") === null) {
//Push the issue object to issues array
issues.push(issue);
//Set the new issues array as a converted JSON object to localStorage
localStorage.setItem("issues", JSON.stringify(issues));
} else {
//Request the issues object and convert to array
issues = JSON.parse(localStorage.getItem("issues"));
//Push new object to issues array
issues.push(issue);
//Set the new issues array as a converted JSON object to localStorage
localStorage.setItem("issues", JSON.stringify(issues));
}
//Reset submit element
document.querySelector("#issueInputForm").reset();
//Run fetchIssue to reflect the new item
fetchIssues();
//Stop default submit
e.preventDefault();
}
//Submit event for the saveIssue function
document.querySelector("#issueInputForm").addEventListener("submit", saveIssue);
//Set the issue status to closed
function setStatusClosed(id) {
var i;
var issues = JSON.parse(localStorage.getItem("issues"));
for(i = 0; i < issues.length; i++) {
if(issues[i].id == id) {
issues.status = "Closed";
}
}
localStorage.setItem("issues", JSON.stringify(issues));
fetchIssues();
}
It all compiles fine in the Closure compiler
The error appears only when hitting the close issue button, so does anyone know why the function is not being properly called in the onclick event (generated via innerHTML method) ?
Any tips welcome, Thanks
Update, I have tried altering the call in the generated innerHTML to escape the quotes but now I get a slightly different error that setStatusClosed() is not defined for the onclick event.(Also I removed Bootstrap so its just using the lib js file.), so there seems to be an error with the onclick call.
issueList.innerHTML += '<div class="well">' +
'<h6>Issue ID: ' + id + '</h6>' +
'<p><span class="Label label-info">' + status + '</span></p>' +
'<h4>' + desc + '</h4>' +
'<p><span class="icon icon-clock"></span> ' + severity + '</p>' +
'<p><span class="icon icon-user"></span> ' + assignedTo + '</p>' +
'Close' +
'Delete' +
'</div>';
Iam currently working with jquery mobile and have an dynamic notification panel. Thereby I want to check the count of character in the text to base the styling on. So for example if text of a notification is > 10 than set height to Xpx.
But what I first do is this:
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
if(category === 'douane'){
douaneHtml = douaneHtml + "<div class='notification-item'>" +
"<div class='ui-grid-a notification-grid'>" +
"<div class='ui-block-a'>" +
"<img class='notification-image' src=" + imgPath + ">"+
"</div>" +
"<div class='ui-block-b'>" +
"<span class='notification-text'>" + shortmessage + "</span>" +
"</div>" +
"</div>";
$('.douane-notification-append').empty().prepend(douaneHtml);
}
}
So basically what I want to do is check:
if ( shortmessage.val().length() > 10 ){
$('.notification-item').css('min-height', '100px');
}
But when I do a console.log(shortmessage.val()); inside the if(category === 'douane') I'll get this in return:
shortmessage.val is not a function
Could someone help me out on this so basically what I want to do is count the characters in shortmessage and based on that do different styling.
This is the output of console.log(info.data[count]);
shortmessage is a String, you need to read the length property :
I've cleaned up with string generation, use an array of strings and join them after. much nicer!
Check if its too short and alter style variable
Then use this in template
for(var count = 0; count < info.data.length; count++){
var shortmessage = info.data[count][3];
var category = info.data[count][4];
var style = '';
// if long message, set the style
if ( shortmessage.length > 10 ){
style = 'min-height: 100px';
}else if ( shortmessage.length > 20 ){
style = 'min-height: 200px';
}else if ( shortmessage.length > 30 ){
style = 'min-height: 300px';
}
if(category === 'douane'){
douaneHtml = [
douaneHtml,
"<div class='notification-item' style='" + style + "'>",
"<div class='ui-grid-a notification-grid'>",
"<div class='ui-block-a'>",
"<img class='notification-image' src=" + imgPath + ">",
"</div>",
"<div class='ui-block-b'>",
"<span class='notification-text'>" + shortmessage + "</span>",
"</div>",
"</div>"
].join('');
$('.douane-notification-append').empty().prepend(douaneHtml);
}
}
If you can, try the new ES2015 strings.
Cleans up code a lot.
douaneHtml = `
${douaneHtml}
<div class='notification-item' style='${style}'>
<div class='ui-grid-a notification-grid'>
<div class='ui-block-a'>
<img class='notification-image' src='${imgPath}'>
</div>
<div class='ui-block-b'>
<span class='notification-text'>${shortmessage}</span>
</div>
</div>`;
Problem : val() method can't be called on string and since the shortmessage contains string message that will throw an error.
Suggested solution : just remove the extra .val() and it will works :
if ( shortmessage.length > 10 ){
$('.notification-item').css('min-height', '100px');
}
NOTE : length is a property so you should remove the () from the length.
Hope this helps.
Currently, I am trying to load all my tweets from the keywords which i search. There are 10 results actually but I am being shown only 3 results and in my console window its showing an error message.
This is the error message:
Uncaught TypeError: Cannot read property 'bounding_box' of null
This is my js code:
(function(){
var location = new Array();
var query = '%23CM0655';
var url = "search.php";
$.post(url, {query:query}, function(tweets){
console.log(tweets);
$("#tweetResult tbody").html("");
var geoEnabled = false;
var placeName = "";
var countryName = "";
for(var i=0; i<tweets.statuses.length; i++){
var row = $("<tr></tr>");
var img = $("<td><div class='div_pic'><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/>"+
"<label class='user_name' hidden>"+tweets.statuses[i].user.screen_name+"</label>"+
"<label class='divlatitude' hidden>"+tweets.statuses[i].place.bounding_box.coordinates[0][0][0]+"</label>"+
"<label class='divlongtitude' hidden>"+tweets.statuses[i].place.bounding_box.coordinates[0][0][1]+"</label>"+
"</div></td>");
//var img = $("<td><div class='div_pic'><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/></div></td>");
row.append(img);
// row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].user.screen_name));
row.append($("<td></td>").html(tweets.statuses[i].text + "<br/>"));
geoEnabled = tweets.statuses[i].user.geo_enabled;
if(geoEnabled){
placeName = tweets.statuses[i].place.name;
countryName = tweets.statuses[i].place.country;
if(placeName != null){
row.append($("<td></td>").html(placeName + "," + countryName + "<br/>"));
}
row.append($("<td></td>").html("Location: " + tweets.statuses[i].place.bounding_box.coordinates[0][0][0] + ", " +
tweets.statuses[i].place.bounding_box.coordinates[0][0][1] + "<br/>"));
row.append($("<td></td>").html(tweets.statuses[i].created_at));
}
$("#tweetResult tbody").append(row)
}
});
setTimeout(arguments.callee, 60000);
})();
This is the line which is showing the error:
"<label class='divlatitude' hidden>"+tweets.statuses[i].place.bounding_box.coordinates[0][0][0]+"</label>"+
Are there any way to solve this error. I want to show all the tweets even the location is not enabled for the certain tweets. Can someone help me on this. Thank you.
I solved it by adding a if-else statement around it
if (tweets.statuses[i].user.geo_enabled && tweets.statuses[i].place != null) {
var img = $("<td><div class='div_pic'><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/>"+
"<label class='user_name' hidden>"+tweets.statuses[i].user.screen_name+"</label>"+
"<label class='divlatitude' hidden>"+tweets.statuses[i].place.bounding_box.coordinates[0][0][0]+"</label>"+
"<label class='divlongtitude' hidden>"+tweets.statuses[i].place.bounding_box.coordinates[0][0][1]+"</label>"+
"</div></td>");
}else{
var img = $("<td><div class='div_pic'><img src='" + tweets.statuses[i].user.profile_image_url + "' class='tweetpic'/>"+
"<label class='user_name' hidden>"+tweets.statuses[i].user.screen_name+"</label>"+
"<label class='divlatitude' hidden>null</label>"+
"<label class='divlongtitude' hidden>"+tweets.statuses[i].user.location+"</label>"+
"</div></td>");
}
Change the following tweets.statuses[i].place.bounding_box.coordinates[0][0][0] to
tweets.statuses[i].place ? tweets.statuses[i].place.bounding_box.coordinates[0][0][0] : "No location data"
Since you are using this snippet at multiple places, i would suggest you to store that in a variable and use it.
In general if you the data object you get can have null or undefined, it is always better to play safe. The above code can be like:
var location = (tweets.statuses[i].place && tweets.statuses[i].place.bounding_box && tweets.statuses[i].place.bounding_box.coordinates[0][0][0] ) || "No location";
Assuming, if you have bounding_box, you will surely be having coordinates[0][0].