jQuery .prepend JSON results to multiple div's - javascript

So I am looping through some JSON and prepending latest results to some HTML on another page. Everything works perfectly code wise, except I am currently prepending everything to one div, where I would like to prepend particular items to particular divs. See below. I would like to echo the name in the name div, content in content div and the id in the message div, for example.
Thanks so much in advance!
My HTML is as follows:
<div id="activityspot">
<div class="entry template">
<div class="message"></div>
<div class="name"></div>
<div class="content"></div>
</div>
</div>
The jQuery is as follows:
$.get(url, function(data) {
jsonData = $.parseJSON(data);
var spot = $("#activityspot");
var template = spot.find(".template");
for (var j = 0; j < jsonData.items.length; j++)
{
var entryData = jsonData.items[j];
var entry = template.clone();
entry.removeClass("template");
//I guess I need to select the other div's in here?
entry.find(".message").text(entryData.statusid + entryData.name + entryData.content);
spot.prepend(entry);
}
What I end up with is something that looks like this:
<div class="message">53671 (id) Billy Zane (name) I like Billy (message) </div>

Try:
entry.find(".message").text(entryData.statusid);
entry.find(".name").text(entryData.name);
entry.find(".content").text(entryData.content);

Related

My newly created html element to show Item Size on each order detail row only shows on the top row

Edited with my progress:
Noob here. I know just enough javascript to get myself in trouble. Case and point: my webstore has an existing template for a packing list and I'm trying to add the item Size to it.
For each ordered item, the packing list has an element [itemname] which contains the Item + Size. I wrote a function that passes [itemname], breaks out just the size, and returns it. I'd like to display that size on the line item beside quantity, or anywhere on the detail line.
The itemSize tag is only showing on the top detail line. It is not inserting where it should.
Spent way too much time on this issue. Can anyone help?
<!--START: items-->
<div class="row">
<div class="invoice-id">[id]</div>
<div class="invoice-items">
[itemname]<!--START: warehouse_location--><br />
[warehouse_location] [warehouse_aisle] [warehouse_bin] [warehouse_custom]<!--END: warehouse_location-->
</div>
<div id="itemSize"></div>
<div class="invoice-qty">[numitems]<br /> </div>
<div class="clear"></div>
</div>
<hr>
<script language="JavaScript" type="text/javascript" >
function myFunction(txt){
var str = txt.substr( txt.indexOf(";")+1, txt.length - txt.indexOf(";"));
console.log(str);
var newDiv= document.createElement("div");
var newContent = document.createTextNode(str);
newDiv.appendChild(newContent);
var currentDiv = document.getElementById("itemSize");
var nextDiv = document.getElementById("invoice-qty");
currentDiv .insertBefore(newDiv, nextDiv );
}
myFunction("[itemname]");
</script>
<!--END: items-->
This is the packing list output. The "bag of 6 tarts" or "7oz med" should be on each line beside the respective item.
Attribute id should be unique. You can generate a dynamic id, something like: id-[index] and then in your JS function target the id that matches each item.
function myFunction(txt, index) {
var str = txt.substr( txt.indexOf(";")+1, txt.length txt.indexOf(";"));
var newDiv= document.createElement("div");
var newContent = document.createTextNode(str);
newDiv.appendChild(newContent);
var currentDiv = document.getElementById(`itemSize-${index}`);
var nextDiv = document.getElementById("invoice-qty");
currentDiv .insertBefore(newDiv, nextDiv );
}

Changing background of one post in a group of posts -JS

I have a page where at top a full post (Wordpress) is displayed and underneath the post is the full group of posts (title and excerpt) including the one displayed. I want to be able to change the background of the post below (title and excerpt) when it is the same post as the one displayed in full above.
Here's my code:
var title1 = document.querySelector(".subhead").innerText.toLowerCase();
var names = document.querySelectorAll('.case-names'),
result = [];
for (var i = 0; i < names.length; i++) {
result.push(names[i].textContent.trim().toLowerCase());
if (title1 == names[i]) {
document.querySelector(".case-bottom").style.backgroundColor = "red";
}
};
When I use console log, I see title1 = joe smith and that "joe smith" is contained in the names array. I don't get any errors but the background isn't changing.
Thanks in advance.
You'd need to put the text in an inline element, like a span, and then apply the background color to the span.
HTML markup:
<h1 class="case-bottom"><span>The Last Will and Testament of Eric Jones</span></h1>
JavaScript:
if (title1 == names[i]) {
document.querySelector(".case-bottom span").style.backgroundColor = "red";
}
I didn't test the code, and I had to guess what is your DOM structure. So my code might not match your need exactly, but it should be enough to show you what you should do. I suppose your HTML:
<div class="main-post"></div>
<div class="case-bottoms">
<div class="case-bottom>
<div class="case-name">Post Title</div>
<div class="case-excerpt">some text</div>
</div>
</div>
let cases = document.querySelectorAll('.case-bottom');
[...cases].forEach(case => {
let caseTitle = case.querySelector(".case-names").trim().toLowerCase();
if (caseTitle == title1) {
case.style.backgroundColor = "red";
// I always prefer this:
case.classList.add(".is-reading");
} else {
// and this:
case.classList.remove(".is-reading");
}
)

JavaScript: Dynamically created html-like string won't tun into html

in DOM I already have a wrapper
<div id="wrapper"></div>
which I need to fill with bunch of divs, where each will represent new category.
Each category will be then filled with various cards representing items of that category. Like this:
<div id="wrapper">
<div data-category="puppy">
Dynamically created category wrapper
<div class="puppy1">...</div>
<div class="puppy2">...</div>
</div>
<div data-category="cat">
...
</div>
</div>
I use following code to create and fill category, but I always end up either having empty category or having a string inside reprenting the html.
var categoryWrapper = document.createElement("div");
categoryWrapper.setAttribute("data-category", key);
categoryWrapper.innerHtml = htmlString;
Here is a fiddle demo of my issue.
https://jsfiddle.net/uuqj4ad5/
I'll be grateful for a help.
There is a typo, innerHml should be innerHTML(Javascript object properties are case sensitive) otherwise it simply add an additional property and nothing gets happened.
categoryWrapper.innerHTML = htmlString;
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
var outerWrapper = $("#wrapper");
var categoryWrapper = document.createElement("div");
categoryWrapper.innerHTML = htmlString;
outerWrapper.append(categoryWrapper);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>
Under this title various categories should be dynamically created
</h3>
<div id="wrapper">outerWrapper waiting for dynamic data...</div>
</div>
FYI : If you want to remove the existing content then use html() method instead of append() method.
innerHtml
should be
innerHTML
Javascript is case sensitive
If you are using jQuery why do you want to mix jQuery and Vanilla JS.
var outerWrapper = $("#wrapper");
// I created new categoryWrapper object
var categoryWrapper = $('<div/>', {
html: htmlString
});
debugger;
// WHen I have the category filled with inner data, I will append it into outerwrapper
outerWrapper.append(categoryWrapper);
jsFiddle
Checkout my fiddle:-
https://jsfiddle.net/dhruv1992/1xg18a3f/1/
your js code should look like this
// This is dynamically filled html template. The data comes from some JSON.
var htmlString = "<div class='card'><div class='cardImg'><img src='http://cdn.cutestpaw.com/wp-content/uploads/2012/07/l-Wittle-puppy-yawning.jpg' alt='Puppy'></div><div class='cardContent'><div class='cardInfo'><p>Puppy Yawning</p></div><div class='cardDesc'><p>Awww!</p></div></div></div>";
// This outer wrapper will in the end contain few categories
var outerWrapper = $("#wrapper");
outerWrapper.append('<div>'+htmlString+'</div>')

replace set of strings in array

Using $('div#top_container').html(), I get the following as an example:
<div class="top" id="top_container">
<div class="example">First</div>
<div class="example">Second</div>
</div>
giving...
<div class="example">First</div>
<div class="example">Second</div>
Here, using .replace(), I want to replace <div class="example"> with *%^% (random set of characters) and remove </div>:
var content = $('div#top_container').html();
var clean_1 = content.replace('<div class="example">','*%^%'); //add $*!#$
var clean_2 = clean_1.replace('</div>',' '); //remove </div>
giving...
console.log(clean_2); --> *%^%First*%^%Second
Now, the number of example div elements can vary and I need to first find out how to target them all. Also is there a cleaner way to target both <div class="example"> and </div> at the same time?
EDIT:
I am not looking to change the html itself, but rather have the edited version as a variable that I can do stuff with (such as send it to php via ajax).
How would I do this?
Use replaceWith() method with a callback and generate prefered text string by getting text content using text() method.
$('div.example').replaceWith(function(v) {
return '%^%' + $(this).text();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="example">First</div>
<div class="example">Second</div>
</div>
UPDATE: If you don't want to update the original element then use clone() and do the remaining thinks on the cloned element.
var res = $('#parent')
// clone element
.clone()
// get element with `example` class
.find('.example')
// update content
.replaceWith(function(v) {
return '%^%' + $(this).text();
})
// back to previos selector and get html content
.end().html();
console.log(res)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div class="example">First</div>
<div class="example">Second</div>
</div>
Create one prototype like :
String.prototype.replaceAll = function (toReplace, replaceWith){
return this.split(toReplace).join(replaceWith);
}
and your jquery code be like :
$("div#top_container").each(function( i ) {debugger;
console.log(this.innerHTML.replaceAll('<div class="example">','*%^%').replaceAll('</div>',' ');)
});
You can use replaceWith function
$(function () {
$(".example").replaceWith(function(){
return "%^%"+$(this).text();
});
});
You can make a clone of container if you don't want to change original div.
var html="";
$(function () {
var newHtml = $("#top_container").clone();
$(newHtml).find(".example").replaceWith(function () {
html+= "%^%" + $(this).text();
});
});
console.log(html);

Get the id numbers (separatly) from the url and use it to select the id with that ID number (using jquery)

I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}

Categories