How to properly set the HTML contents using Jquery? - javascript

I have this javascript code where it goes for each movies in jsonp dataType. For each movies I have to display its thumbnail image and its title together with the star rating. To display the star symbols below for each movies I have this code:
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
It simply sets the html content of the class prediction to this -> <div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>
I tried to use this on directly on my html code and it is fully working I can see the stars. Here it is:
But I tried this on javascript and it is not displaying. I just want to have ratings below for each and every movies.
This is my javascript code:
var html = '';
var count = 0;
$.each(data.movies, function(index, movie) {
html += '<div class="item col-xs-6 col-md-3">';
html += '<div class="thumbnail" style="min-height:320px;max-height:320px;">';
//add link here
html += '<a href="viewMovieDetails.php?id=' + movie.id + '">'
html += '<img src="' + movie.posters.detailed + '" style="width:175px; height: 230px;" class="img-responsive" alt="" ></a>';
html += '<div class="caption">';
html += '<h5>' + movie.title + '</h5>';
html += '<div class="prediction"></div>';
html += '</div></div></div>';
//set a delay (1second) for a call on rotten tomatoes api and
//store data on db
if(count > 5){
setTimeout(function() { storeDataOnDB(movie.id);; }, 1000);
count = 0;
}
else{
count++;
}
});
// Append movies
$('#movie_recommend').html(html);
var include = '<div class="rateit" data-rateit-value="2.5" data-rateit-ispreset="true" data-rateit-readonly="true"></div>';
$(".prediction").html(include); //DISPLAYS THE PREDICTION RATING
What do you think is wrong? Am I missing something? or is there other way to do it. Thanks for the help.

You should notify RateIt plugin, that new data is available, just add this:
$(".rateit").rateit();
after $(".prediction").html(include);

Related

how to replace data?

Good day.I deduce 50 blocks. Receive information from a file in JSON format.
I get a link to a photo from JSON. I give it to the page. I need to change all the photos large on the small size photos in just one click.
Please tell me how to change the link everywhere at once?
var image = data["info"][i]["img"]["big"];
block += '<img src="' + image + '"/>';
//image - link to photo
If all the images are displayed inside a single element like this
<div id="gallery">
<img ... >
<img ....>
.....
</div>
Then you could regenerate the entire contents of the div:
var str = "";
for (var i = 0; i < data["info"].length; i++) {
str += '<img src="' + data["info"][i]["img"]["small"] + '"/>';
}
document.findElementById("gallery").innerHTML = str;

Jquery attribute not being added to div element

I have a div as follows
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
I am trying to add an attribute to #t1 in the following function.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
But the attribute is not being added. I am not getting a text in the tooltip. what's the issue here?
Note that noOfDatasets is 0.
To answer your question, the issue in your code is the order is is executed.
When the function appendCreateprojectDisabled(noOfDatasets) is executed, it looks for the element $("#t1"), which does not exists yet since the following string has not been added to the HTML document yet:
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
As you may notice, the above code has the element id="t1", which doesn't exists at the time the function appendCreateprojectDisabled(noOfDatasets) is called.
You created the div here dynamicly in javascript, so you just have a string here.
There is two way for you.
First you should write in on the page.
var htmlString = '<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>';
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
$("#aDivInYourPage").html(htmlString);//after register your div you can find your 't1' div. if not it will be undefuned for you.
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
The other way is you can put a spetial character to your div like {TitleAttribute} and replace this with your attribute like title='No datasets available'
you can achieve this by parsed the string to HTML element.
Try this code.
$(document).ready(function () {
function appendCreateprojectDisabled(noOfDatasets, divElement) {
var classAppend = '';
if (noOfDatasets == 0) {
divElement.find("#t1").attr('title', 'No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
var divElement = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'</div>' +
'</div>'
divElement = $(divElement);
var paraElement = '<p><span>Create Project</span></p>'
divElement.find("#t1").append($(paraElement));
$(document.body).append(divElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
Do something like this:
var classAppend = "";
var classAppend = appendCreateprojectDisabled(noOfDatasets);
After making sure classAppend have some value; you can append your html wherever you want.
var html = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'<p><span>Create Project</span></p>' +
'</div>' +
'</div>';
Use this piece of html wherever you want now. The below function is called first.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}

Creating jquery menu - json response

I've created a bootstrap menu from a json response. The menu gets the list of items and creates a link to https://example.com/api/products/GetProductDetail/product_id which takes you to the json response.
What I need it to do is not follow the link to the json response, but rather get that response, parse the data and plug it into a div on the existing page, but I'm not sure how to do that.
Here is what I have right now:
<script>
$.getJSON('https://example.com/api/products/GetProductList/', function(data) {
var output = '<div class="panel panel-default">';
for (var i in data.Categories) {
output += '<div class="panel-heading '+data.Categories[i].category_id +'"><a data-toggle="collapse" data-parent="#accordion" href="#' + data.Categories[i].category_id + '-products">';
output += data.Categories[i].Category + '</a></div>';
output += '<div id="' + data.Categories[i].category_id + '-product" class="panel-collapse collapse"><div class="panel-body">';
for (var j in data.Categories[i].Products) {
output += '<li>'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</li>';
}
output += "</div></div>";
}
output += "</div>";
document.getElementById("accordion").innerHTML = output;
});
</script>
Instead of creating a link to the product detail url, create a link to some function accepting the productid.
This function could make a call just like the one you currently have for the product list, processing the json and appending the result to a div.
So add a function like:
function getProduct(id) {
$.getJSON('https://example.com/api/products/GetProductDetail/' + id, function(data) {
//Process JSON to some HTML.
var productDetails = '<div>' + data.Product.Name + '</div>';
//Add it to the div where you want your product details to appear
document.getElementById("detailsDiv").innerHTML = productDetails;
};
}
and replace the li, created for every product in the overview with something like the following:
output += '<li><a onclick="getProduct(' + data.Categories[i].Products[j].product_id + ');">'+data.Categories[i].Products[j].short_description + " -- " + data.Categories[i].Products[j].cost+' coins</a></li>';

Load JSON data using the dropdown menu and refresh the div area with the new results in a web site

I am trying to load JSON data from a drop down menu to a div area which would be refreshed with the new results, i have manged to get the data and show it in the div area without using the drop down menu, but cannot find a way to call the required data using the drop down menu.
the below code is to bring up part of the json data from the json file that is present which is working when i load the web page, but what i need is that when the user clicks on the drop-down menu and clicks any of the links, the relevant json data will be displayed
$(function loadpc()
{
$(document).ready(function () { // load json file using jquery ajax
$.getJSON('PCproducts.json', function (data) {
var output = '<div id="row">';
var count = 1;
$.each(data.pc, function (key, val) {
output += '<div id="holding-area">';
output += '<div id="img-area">' +
'<img id="img" src="'+val.imgpath+'" alt="'+ val.title +'" /></div>';
output += '<div id="info">';
output += '<h2>' + val.title + '</h2>';
output += '<p>' + val.category + '</p>';
output += '<p>' + val.develop + '</p>';
output += '<p>' + val.released + '</p>';
output += '<p>' + val.price + '</p>';
output += '<p>' + val.quantity + '</p>';
output += '<p><input type="submit" value="Add to cart" class="btn" /></p>'
output += '</div>';
output += '</div>';
if(count%2 == 0){
output += '</div><div id="row">'
}
count++;
});
output += '</div>';
$('#content-2-1').html(output); // replace all existing content
});
});
});
Can anyone please guide me in the right direction as i have been trying for a long time with no success
Using jquery template is the simple manner :)
You may find some info there jquery template documentation
jquery template is a simple type formatted like this i took it from one of my project:
<script type="text/x-jquery-tmpl" id="tplmsg">
<div class="row">
<div class="col-xs-3 col-md-1">
<img src="${src}" class="img-thumbnail" alt="${title}" />
</div>
<div class="col-xs-9 col-md-11">
<div class="col-xs-12 col-md-12">
<p class="title">${getSubstring(title,0,100)}</p>
</div>
<div class="col-xs-12 col-md-12 btf" >
<p class="adsdts"><strong>Data: </strong>${parseJsonDate(DateAdd)}
<strong>Prezzo:</strong>${price}
<strong>Provincia:</strong>${pvname}
<%--<strong>Provincia:</strong>${pvname}--%>
</p>
</div>
</div>
</div>
<hr />
</script>
In abovesnippet you may see some stuff which is vbnet related how ever logic is the same.
Then you may fill it with simple js function like this:
function getAds(task,token) {
var qry='task='+task+'&token=' +token;
$.ajax(
{
type: "POST", url: url, data: qry
,
success: function (msg) {
if (msg.hasOwnProperty('error')) {
$("#").html(msg.error);
return;
}
else if (msg.hasOwnProperty('empty')) {
$("#result").html(msg.empty);
return;
}
else {
//reular version
$("#"+msg.tmpl).tmpl(msg.data, null).appendTo("#"+msg.result);
}
},
error: function (msg) {
$("#result").html("errore durante l'elaborazione");
}
});
}
That's all simple and fast.

how to give id dynamically to an element in phonegap?

Hi i am doing an application in phonegap,in that application i need to show list of the users in the listview contains profile pic,name,number and online status .
for (var i = 0; i < roster_items.length; i++) {
var jid_contact=roster_items[i].getAttribute('jid');
var name_contact=roster_items[i].getAttribute('name');
/// Add all the contacts to Array
$('#contacts-listview').append(
'<a href="#" onclick="user_contactsClicked('+ i + ');">' +
'</br>'+
'<div id="contact_img">'+
'<img id="splash" src="images/contact_default_pic.png" />'+
'<ul id="menu">'+'<li id="contact">'+name_contact+'</li>'+
'<li id="status">'+jid_contact+'</li>'+'</ul>'+
'<div class="pull-right"><div><img id=i class="status_img" src="images/user_online.png" /></div>'+
'<div style="margin-bottom: 10px;"><ol id="date">'+
'<li>date</li>'+
'<li>time</li>'+
'</ol></div></div>'+
'</div>'+
'</br>'+
'</a>'
);
}
and i will call a function for changing the online status for a particular user and changes the image
changeOnlineStatus_contact : function(elementPos) {
alert(elementPos);
if(elementPos>=0) {
//Get current table
document.getElementById(i).src = "images/user_offline.png";
}
}
for this i want to give if for the img element dynamically. Please suggest me.
Thanks in advance..
The reason the id isn't getting set on the image is because you've got:
"…<img id=i class=…" which means that every image has the id of "i"
If you changed this to:
"…<img id=\""+i+"\" class=…" then it would use the value of i as the id attribute
If you have more complex bindings to the UI, I'd recommend looking at something like http://knockoutjs.com/ - this way you would update the underlying model, and the html would automatically be updated to represent it.

Categories