Jquery attribute not being added to div element - javascript

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;
}

Related

Append elements based on its parent and children from recursive function in Javascript

I'm getting all comments for a post in subreddit and I need to display them in Reddit style.
It means every comment has its parent and children. I try to display them with the following structure.
<div class="comment" id="comment.id" >
<div class="body> comment.body </div>
<div class="replies> Add one level lower comments </div>
</div>
To structure everything I use this recursive function, but I struggle with appending comments on the page.
Here is http://jsfiddle.net/DHKtW/572/
And this is an example for what design I'm trying to achieve, but not in the proper way - http://jsfiddle.net/DHKtW/573/ Instead of this, it should just insert all child comments under <div class="replies> </div>
$.getJSON("http://www.reddit.com/r/science/comments/40h4go.json?", function(data) {
console.log(data[1].data.children);
checkComments(data[1].data.children,0);
});
function checkComments(comments, deep) {
var replies = '<div class="replies"> </div>';
for (comment in comments) {
console.log(comments[comment].data,deep);
element = comments[comment].data;
var body = '<div class="body"><p>' + element.body + '</p></div>'
var $comment = $('<div id="comment-'+element.name+'" class="comment"> 'body + replies +' </div>');
child_comments = comments[comment].data.replies;
if (child_comments) {
checkComments(child_comments.data.children,deep+1);
}
}
}
.replies {
margin-left: 20px;
}
If I am not mistaken of what you're trying to achieve.
I had to rename some of your variables because it misled me.
$.getJSON("http://www.reddit.com/r/science/comments/40h4go.json?", function(data) {
addComments($('.comments'), data[1].data.children);
});
function addComments(parentElem, comments)
{
for (comment in comments)
{
var commentData = comments[comment].data;
var bodyElem = '<div class="body"><p>' + commentData.body + '</p></div>';
var $commentElem = $('<div id="comment-' + commentData.parent_id + '" class="comment" style="margin-left: 10px">' + bodyElem + '</div>');
parentElem.append($commentElem);
if (commentData.replies)
{
var $replyElem = $('<div class="replies"> </div>');
$commentElem.append($replyElem);
addComments($replyElem, commentData.replies.data.children);
}
}
}
Here's the FIDDLE

How to properly set the HTML contents using Jquery?

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);

Pass string from one function to the next javascript

I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;

element.html() return empty on DOM ready

I am working on a countdown timer, using http://keith-wood.name/countdown.html.
My code looks like this,
$('.clock').countdown({until:new Date(2012, 11, 31), format: 'odHMS', onTick:watchCountdown, tickInterval:5, layout:
'<div id="timer">' +
'<div id="timer_labels">'+
'<div id="timer_months_label" class="timer_labels">Months</div>'+
'<div id="timer_weeks_label" class="timer_labels">Days</div>'+
'<div id="timer_days_label" class="timer_labels">Hours</div>'+
'<div id="timer_minutes_label" class="timer_labels">Minutes</div>'+
'</div>'+
'<div id="timer_months" class="timer_numbers"><span class="divide"></span><span>{onn}</span></div>'+
'<div id="timer_days" class="timer_numbers"><span class="divide"></span><span>{dnn}</span></div>'+
'<div id="timer_hours" class="timer_numbers"><span class="divide"></span><span>{hnn}</span></div>'+
'<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span>{mnn}</span></div>'+
'</div>'
});
As you onTick I call a function that looks like this,
function watchCountdown(periods) {
var $div = $("#monitor");
var html = $div.html();
var checking = setInterval(function() {
var newhtml = $div.html();
if (html !== newhtml) {
myCallback($div);
}
},100);
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
}
In the function above there is a check for html != newhtml however html is returning as an empty variable evening though there is HTML in the #monitor element. How can I make it realise there is content to check against?
You don't understand what is DOM ready, it fires only once, when the DOM is fully loaded and rendered from the server.
If you change the DOM with javascript, it has no effect on the DOM ready event.
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
The code above will not cause delay or trigger again the DOM ready event.

Adding html elements from variable using jquery?

I am trying to add elements to specific div, but not using clone(), because i need fresh copy of original elements on every add, mainly because elements are draggable and their values are being change by user? So i have my html in variable, i need to take this elements and add them on click to another elem. ?
$(document).ready(function (e) {
var $gElem = $(
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
);
$('.mainSearch').html($gElem); // initial load of element
$("#combobox100").combobox();
$("#combobox200").combobox();
var counter = 1;
$('.add').live('click', function () {
if ($('.distributionWrapper').length === 6) return;
//var el = $('.distributionWrapper:first').clone().attr('id', 'element_' + ++counter).appendTo('.mainSearch');
$('.mainSearch').add($gElem).attr('id', 'element_' + ++counter);
// here on click add gElem to .mainSearch and set atribute to .distributionWrapper
});
$('.clear').live('click', function () {
if ($('.distributionWrapper').length === 1) return;
$(this).parents('.distributionWrapper').remove();
});
});
Any ideas?
try this
$('.mainSearch').append($gElem);
$('.mainSearch').children('.distributionWrapper:last').attr('id', 'element_' + ++counter);
Store the html as a string in a javascript variable and create a jQuery element every time you need one from that string.
var elemHtml =
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
$(function(){
//your initial element
var $elem1 = $(elemHtml);
}
function someHandler(){
//you can create fresh new elements anywhere without cloning
var $elem2 = $(elemHtml);
}
The duplicate IDs need to be removed. But that's outside the scope of your question.

Categories