Add image and text to list in html from JSON - javascript

My use case is to add image and a text dynamically to list. All I have is JSON (extracted from DB as result set). The JSON structure is as mentioned below:
[{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
So, in my java script, I append this list to a HTML body through the following code:
<script>
$(document).ready(function(e) {
var data = [{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val.Comment + '</li>');
});
$('<ul/>', {
html: items.join('')
}).appendTo('body');
});
</script>
Here, I am trying to bring an image (whose filepath is available in the JSON) to the list. So, the list should contain image (may be a smaller one - I shall use styling for this) and the comment side by side.
Please can someone help?
EDIT:
I tried this: I am building the list runtime.. So, i tried using
before val.comment.. it doesnt seem to work. Any words on this?

In order to show image with each list item you should have to add img tag in your list item. The JS code should be like below:
items.push('<li id="' + key + '"><img src="' + val.FilePath + '" />' + val.Comment + '</li>');
Hope this will help !!

In your items.push add the <img> tag and output the value from your FilePath field:
items.push('<li id="' + key + '">' + val.Comment + '<img src="' + val.FilePath +'" alt="" />' + '</li>');

Related

HTML Element not being inserted

I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.

Why jQuery append() removes words after first blank space in string

I'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>

How to track order in ordered list that has one looping list item fed different parameters

I'm populating a list of YouTube videos. I want the list to be ordered by number. The thing is, my ordered list only has one list item. That item is looped through with Jquery.each and is given a different value with each iteration.
The way it is coded in my example below, every list item listed as number 1.
$.each(results, function(index,value) {
html += '<ol><li><a data-video- type="https://www.youtube.com/embed/' + value.id.videoId + '?autoplay=1"> <img src="' +value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '</a>)</li><ol>'; });
$('#results').html(html);
You can short your results before adding to ol. Then you can add like following:
html = "<ol>";
$.each(results, function(index,value) {
html += '<li><a data-video- type="https://www.youtube.com/embed/' + value.id.videoId + '?autoplay=1"> <img src="' +value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '</a>)</li>';
});
html += "</ol>";
$('#results').html(html);
You should change your code. Append each list to ul.
$.each(results, function (i) {
$('<li>').appendTo('.orderedList'); //Class of `ul`
}

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Adding a link to a <td> element while parsing json?

Another noob question/issue.....I am currently parsing a json file and appending the data to an HTML table. I need to make one of the name/value pairs (COPD_QUAL.FIN) display as a link within the table.
Here is my function to append the data....
function createPatientTable(json) {
$.each(json.LIST, function(i, COPD_QUAL) {
$('.footable > tbody:last').append('<tr><td>' + COPD_QUAL.PATIENT + '</td><td>' + COPD_QUAL.FIN + '</td><td>' + COPD_QUAL.NURSE_UNIT + '</td><td>' + COPD_QUAL.ROOM + '</td><td>' + COPD_QUAL.BED +'</td><td>' + COPD_QUAL.ATTENDING_PHYS + '</td><td>' + COPD_QUAL.LENGTH_OF_STAY + '</td><td class="assessment ' + getSeverity(COPD_QUAL.MED_ASSESS) + '">' + COPD_QUAL.MED_ASSESS + '</td></tr>');
});
$('.footable').footable();
};
This is the part I am trying to make a link but receiving a syntax error when clicking the link within the application that I included the table within:
'</td><td><a href="javascript:APPLINK(0,"powerchart.exe","/PERSONID=8986122 /ENCNTRID=14150574")">'
If I try to use single ' instead of the double " within the () of the APPLINK function, I receive an unexpected ) error:
'</td><td>' + COPD_QUAL.FIN + '</td><td>'
Could someone help me with the syntax? Am I completely off here? I was able to get the link to work otuside of the table in a random div but I cannot append the link to the table within my json function. Here is the hardcoded / standalone div link that works:
Open patient chart test2
Thanks in advance!!!
'</td><td>' + COPD_QUAL.FIN + '</td><td>'
or
'</td><td><a href="javascript:APPLINK(0,\\"powerchart.exe\\",\\"/PERSONID=8986122 /ENCNTRID=14150574\\")">'
You need to escape the quotes.

Categories

Resources