How can I set the URL value in my JSON file to a hyperlink when displayed in the table?
JSON
{
"one": "http://urltovideo.mp4",
"two": "The second list item",
"three": "The third list item"
}
jQuery
$.getJSON( "test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<div class='panel panel-default'><div class='panel-heading'>" + key + "</div><div
class='panel-body'><a href=''>" + val + "</a></li></div></div>" );
});
$( "<ol/>", {
"class": "my-new-list",
html: items.join( "" )
}).fadeIn(900).appendTo( "body" );
});
You need to check if val is containing a link:
$.each( data, function( key, val ) {
var link = (val.indexOf('http') > -1) ? '' + val + '' : val;
items.push( '<div class="panel panel-default"><div class="panel-heading">' + key + '</div><div
class="panel-body">' + link + '</li></div></div>');
});
Also, for cleaner code, you should use " for HTML attributes like class="..." and ' for Javascript strings, like: '<a href="' + val + '">'
See jsFiddle
Related
I am trying to do an api call to get a list of subcategories.
my json looks like this
{
"description": "Flower",
"name": "Flower",
"parent_id": "1"
},
{
"description": "Moon",
"name": "Moon",
"parent_id": "1"
}
]
This is what i have attepted so far.
<script type="text/javascript">
$('button').click(function() {
$.ajax({
url: "/api/subcategories?sstr=ball",
dataType: 'json',
type: "GET"
})
.done(function(data) {
$('.results').append('<ul class="list"></ul>');
$.each(data, function(key, value) {
console.log(data)
$('.list').append('<li>' + key + ': ' + value + '</li>');
});
})
.fail(function(event) {
alert(event.status);
});
});
</script>
The result i get is
0: [object Object]
1: [object Object]
2: [object Object]
what i would like is the list of names.
Where value is the array element which is an object instead get its name property.
$('.list').append('<li>' + key + ': ' + value.name + '</li>');
Since it's an array you can use JavaScript Array#forEach method also.
data.forEach(function(value, key) {
$('.list').append('<li>' + key + ': ' + value.name + '</li>');
});
Or you can reduce it to a single append statement by generating the HTML string using Array#map and Array#join methods.
$('.results').append(
'<ul class="list">' +
data.map(function(value, key) {
return '<li>' + key + ': ' + value.name + '</li>');
}).join('') +
'</ul>'
);
First you need to parse your json string to convert it in a javascript array.
So do this -> var json_data = jQuery.parseJSON(data);
Now,
var html = "";
html += '<ul>';
$.each( json_data, function( key, value ) {
html += '<li>'+key+':'+value['name']+'</li>';
});
html += '</ul>';
$('.list').html(html);
I think that will do the trick.
Because my other question, didn't solved my issue, and i tried everything what i know, and every time i am getting more stuck. Please combine this question with my other.
I am building my movie library.And i have two pages, index and movie.html.
Index.html will a page where will display movie items, each item, will have a name, a picture, score, short summary and director and screenplay names.And, also i will have a name from author, if the movie is based from book. All of that is taken from JSON file, that i have created locally.
In other html page, movie.html, i am planning to have more fancy design with more information. Like:wins, synopsis,cast and their characters, etc.
But here is the problem i am facing.
What I have tried:
I have this so far in
index.html
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
for ( var key in data[ i ] ) {
if ( key === "novel" ) {
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="novelAuthor">" + "<p class="NovelTxt">" + "Novel by" + " " + data[ i ].novel +"</p>" + "</div> " +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Directed by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
if(!data[i].novel){
$( '#jsonLoad' ).append( '<a href="movies.html?id='+data[i].id+'" class="itemsHolder">' +
"<div class="titleHolder">" +
"<h2>" + data[ i ].name + "</h2>" +
"</div>" +
"<div class="posterHolder">" + data[ i ].posterPath + "</div>" +
"<div class="summaryShort">" + data[ i ].summary + "</div>" +
"<div class="raiting"><p>" + data[ i ].imdb + "</p></div><div class="genderMovie"> " + data[ i ].gender + "</div> " +
"<div class="directorNdScreen">" + 'Director by ' + " <p class="director">" + data[ i ].director + '</p>' + ' ' + ' Screenplay by ' + "<p class="screenplay">" + data[ i ].screenplay + "</p>" + "</div>"
+ "</a>" )
}
}
} )
} );
My JSON file, i have 20 objects, i will post just 2.
[
{
"id": 1,
"name": "Harry potter and the Sorcerer's Stone",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP1/StillPhoto/StillPhotoBackground.jpg'/>",\
},
{
"id": 2,
"name": "Harry potter and the Chamber of Secrets ",
"year": 2001,
"movieStill" : " <img src='imgsMovie/HP2/StillPhoto/StillPhotoBackground.jpg'/>",\
}
]
And my movie.html looks like this.
$( document ).ready( function () {
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
} );
} );
I know in my movie.html i loop in every object.
How can i write an if statement, that will take per one object with own id, and display what is there.
Here, when i click on Harry potter 1 item, i got two images, from hp1 and hp2,
i just want to show only the one value from item i have clicked. And this means also for the rest of the properties, like different director etc, just to name a few.
It looks like in your movie.html you are just appending the images to .MovieInfo, which would not separate them out but have them all lumped together. You can instead read the id of from the data argument and only display the id associated with the movie you clicked.
Since you are already passing in a GET query to the url (movies.html?id=) you can just grab the value of id from the GET query and start with that (let's call it getID() for now). Afterwards just wrap the .MovieInfo append statement with an if statement checking the data argument for that value.
$.getJSON( "js/appjson.json", function ( data ) {
for ( var i = 0; i < data.length; i++ ) {
if (data[i].id === getID()) {
$( '.MovieInfo' ).append(
"<div class="imgStill">" + data[ i ].movieStill + "</div>"
)
}
}
});
I am trying to apply filtering to a dataTables table using select boxes. I found the following code which allows me to setup the select boxes and filter based on the column data:
https://datatables.net/examples/api/multi_filter_select.html
This code worked perfectly, however I am now using the render method to pull all the columns together into one. We are doing this so we can style each row to create a single 'Ticket'.
Unfortunately now the filtering does not work. I imagine it may be a result of the columns no longer displaying but would appreciate some direction and help :)
Current Code:
$('#ticket_list').DataTable( {
"columnDefs": [
{
"render": function ( data, type, row ) {
return '<span class="client-data"> ' + data + ' </span>'
+ '<span class="priority-data"> ' + row[1] + ' </span>'
+ '<span class="status-data"> ' + row[2] + ' </span>'
+ '<div class="subject-data"> ' + row[3] + ' </div>'
+ '<i class="fa fa-user"></i><span class="agent-data"> ' + row[4] + ' </span>'
+ '<span class="date-data"> ' + row[5] + ' </span>';
},
"targets": 0
},
{ "visible": false, "targets": [ 1,2,3,4,5 ]}
],
"columns": [
{ "title": "" }
],
"pageLength": setPageLength(),
"dom": '<"#search-box"f> rt <"#pagination.col-xs-12"p> <"#table-information.col-xs-12"i>',
language: {
search: "_INPUT_",
searchPlaceholder: "Search"
},
initComplete: function () {
this.api().columns([0,1,2]).every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( ".ticket-filtering" )
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
console.log(val)
column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );
column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
},
} );
CAUSE
You render function returns HTML string unconditionally disregarding the type argument but this function is used to get the data for multiple purposes: displaying, ordering, filtering, type detection.
SOLUTION
Use type detection in render function and only return HTML when data is needed to be displayed (type === 'display').
"render": function ( data, type, row ) {
if(type === 'display'){
data = '<span class="client-data"> ' + data + ' </span>'
+ '<span class="priority-data"> ' + row[1] + ' </span>'
+ '<span class="status-data"> ' + row[2] + ' </span>'
+ '<div class="subject-data"> ' + row[3] + ' </div>'
+ '<i class="fa fa-user"></i><span class="agent-data"> ' + row[4] + ' </span>'
+ '<span class="date-data"> ' + row[5] + ' </span>';
}
return data;
},
DEMO
See this jsFiddle for code and demonstration.
What I'm trying to do is to fill a table with some info from JSON file big.json, I need to do this with jQuery.
It looks like this now but not working:
<div class="stink">
<table>
<tr>
<th>Car</th>
<th>fault1</th>
<th>fault2</th>
</tr>
<script>
$.getJSON( "data.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
</script>
</table>
</div>
the JSON file structure is:
{
"Mercedes": {
"fault1":"not working",
"fault2":"key issues"
},
"BMW": {
"fault1":"not starting",
"fault2":"control problem"
}
}
How can I parse in the table those info with JQUERY ?
As you have a table, you'd better not show your info with lists, but use the table. With this:
$.getJSON( "data.json", function( data ) {
$.each( data, function( key, obj ) {
var items = [];
items.push( "<td>" + key + "</td>" ); //Car name
items.push( "<td>" + obj.fault1 + "</td>" ); //fault1
items.push( "<td>" + obj.fault2 + "</td>" ); //fault2
$( "<tr/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( ".stink table" );
});
});
I tried to modify your code at little as possible so you understand it better.
I need to modify some code already in place. There's a block of code that filters a JQuery list using the URL to populate the search input.
E.g.
http://***/store/mobile/page/productList.page?search=football
Automatically enters "football" in the search bar.
Now I'd need to filter the list, without using the search bar.
So lets say my URL would look something like this :
http://***/store/mobile/page/productList.page?football
This would filter the list with football without using the search bar.
Here's the code I need to change. Please tell me if my question is unclear.
$('div[data-url*="productList"]').live("pageshow", function() {
filterValue = getParameterByName("search", location.search);
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
});
and:
$.each(catalog.products,
function(index, value) {
if ((!filterValue )
|| value.name.toUpperCase().indexOf(filterValue.toUpperCase()) != -1
|| value.brand.toUpperCase().indexOf(filterValue.toUpperCase()) != -1)
{
items.push('<li id="' + index + '">' +
'<a data-identity="productId" href="./details.page?productId=' + index + '" >' +
'<img class="ui-li-thumb" src="' + value.thumbnail + '"/>' +
'<p>' + value.brand + '</p>' +
'<h3>' + value.name + '</h3>' +
'<span class="ui-li-count">' + value.price + ' $</span></li>') +
'</a>';
}
});
if there will always be only 1 parameter after ? than you could simply get it from page location in javascript, e.g.
var url = document.location;
var params = url.split("?");
filterValue = params[params.length-1]
if (filterValue) {
$('input[data-type="search"]').val(filterValue);
}
refreshList();
example: http://jsfiddle.net/yPgPc/