using jQuery .each on a javascript variable before appending to screen - javascript

If i have some basic html that is saved in a variable $html and I want to use an each (jQuery) statement on it before appending to the page and I want to look in this string for each instance of a class and ammend $html.
This is what I was thinking...
$('.flipper', $html).each(function(){
var frontContent = $(this).find('.front > .content');
var backContent = $(this).find('.back > .content');
$(this).append('<div class="background"><div class="content">' + frontContent.html() + '<div class="back">' + backContent.html() + '</div></div></div>');
console.log($html);
});
this doesnt run - i guess because i am trying to update an element on the page rather than one stored in a variable
can I still use the each ?
Cheers

Looks like $html is a string, not a dom element reference... in that case changes made to the elements in the loop will not be reflected in the original string.
Try something like
var html = '';
var $html = $(html);
$('.flipper', $html).each(function () {
var frontContent = $(this).find('.front > .content');
var backContent = $(this).find('.back > .content');
$(this).append('<div class="background"><div class="content">' + frontContent.html() + '<div class="back">' + backContent.html() + '</div></div></div>');
});
console.log($html[0].outerHTML);
Demo: Fiddle

Try this:
$($html).find('.flipper').each(....);

Related

How to concatenate and pass parameters values in html using jQuery

I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

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;

jquery .find and append img tag

I am trying to load pictures name from a xml object and append to div. I am getting confuse with append typing layout, not able to find where im doing typing mistake.
This is working
$("#nn").append("<img id='theImg' src='/pic/jas/pic1.jpg'/>");
This not working
$("#nn").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
My jquery script part is
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var pic_infoVar = xml.find("pic_info");
pic_infoVar.each(function () {
var customer = $(this);
$("#picDiv").append("<img id='theImg' src='/pic/jas/'" + customer.find("pic_name") + "/>");
});
$("#loader").hide();
}
Html Div tag
<div id="picDiv">
LoadPic
</div>
Provded that pic_name is infact an element in an XML data structure (ex: <pic_name>pic1.jpg</pic_name>), the code that will do what you want is:
$("#nn").append("<img id='theImg' src='/pic/jas/" + customer.find("pic_name").text() + "'/>");
This is how i used to do
document.getElementById('nn').innerHTML +='<img src="'+customer.find(\"pic_name\")+'"/>';

Passing javascript variable to jquery

Im facing some problems what i cannot solve for days now.
I wish to get the Position of an element which is have a uniqe ID
Code:
function e_div_show(sid,ctd)
{
var b_fos="t"+sid;
var pos = $(b_fos).offset();
alert(pos.top + ' ' + pos.left);
}
HTML Code:
<?php
...
echo ('<td ID="t'.$array['S_ID'].'">...</td>
...
?>
this is not working..
if i replace the ID to "b_fos" and i comment out the //var b_fos="t"+sid; it working fine.. however in this case the TD ID wont be unique becouse of the php array which generating the code.
Any help please how to define the pos correclty with a javascript variable?
Try changing:
var b_fos = "t" + sid;
To
var b_fos = "#t" + sid;
Try this code you have miss '#' before
function e_div_show(sid,ctd)
{
var b_fos="#t"+sid;
var pos = $(b_fos).offset();
alert(pos.top + ' ' + pos.left);
}

Categories