How do I retrieve information stored in a js file? I assume I am labelling my node elements in HTML incorrectly
I'm hoping to gain a better understanding of how to retrieve a function node from localStorage
Below are the key factors I am trying to get using getElementById into local storage from post HTML.
This is not everything in my listing.html document, I have excluded everything but what I think are essential elements
<div class="listing">
<div class="container-form">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="img" value(src)="1" id="img" src="images/4.JPG" alt="img1">
</div>
<div class="infoBox">
<h5 post="weight" id="weight" value="7.00">7.00 : Under - 16 oz</h5>
</div>
<div class="column-bottom">
<div class="add-button">
<div class="add-button" method="post">
<p><input type="submit" onclick="addListing()" class="btn"></input></p>
<div class="buy-button">
<span class="price" post="price" id="price" value="60">$60</span>
<button type="button" class="btn" onclick="window.location.href='cart.html'" onclick="addListing()"
;>BuyMe</button>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to use the function below to store each element from the post HTML
function addlisting() {
let listing = ['listings'];
if (localStorage.getItem('listings')) {
listing = JSON.stringify(localStorage.getItem('listings'));
alert("added!");
}
listing.push({ 'listingId': listingId + 1, image: '<imageLink>' });
listingsId = listingsId + 1;
var listingsName = document.getElementById('name').innerHTML;
var listingsPrice = document.getElementById('price').getAttribute('data- value');
var listingsImage = document.getElementById("img").src;
var listingsWeight = document.getElementById('weight').getAttribute('data- value');
value = parseFloat(listingsPrice, listingsWeight).toFixed(2);
localStorage.getItem('name', 'price', 'img', 'weight', JSON.stringify(listingsName, listingPrice, listingsImage, listingsWeight));
}
here is the $(document).ready(function(){ function I'm hoping to implement into my code, I got this from another Stack Overflow page as it was the most fitting however I am yet to understand each component.
$(document).ready(function () {
$('#Btn').load(function () {
let listings = [];
if (localStorage.getItem('listings')) {
listings = JSON.parse(localStorage.setItem('listings'));
}
listings.push({ 'listingId': 1, image: '<imageLink>' });
});
});
my question again is how do I then execute this function using onload Onto a separate HTML, called cart.html. I did not display my cart.html file because there is nothing pertaining to this question on it. And furthermore how to go about styling Onload events that retrieve information from localStorage.
P.S.
There is an alert function within my first .js excerpt addListing(), that does not fire when clicked. probably a sign of bad programming. I've just never found a straightforward answer
Related
That's my first ever question, and it's about my very first project, it's an online RPG Forum/PlayByChat game. I know it's kinda of an ambitious project.
So, i'm stuck from months into a problem that i feel i'm close to solve, premise (I'm self-taught).
The idea is to activate an if statement by a keyword/password given by an NPC, if there isn't no keyword in the message that it's supposed to be sent, then nothing should to happen.
That's what i've been able to put together and modify a little bit (it's not the entire code, just the interested parts), it works but it gets activated by any words or even by just one letter/empty messagges, i recently added the attribute "required" to the textarea so the field needs to be fill before to send messagges (even though it works only for the first click, then gives the possibility to send empty messagges which of course triggers the JoinedInTheRoom function) but anyway, that's a minor problem, the main problem remains that i cannot figured out how to make work the if statement inside the event listener under the JoinedInTheRoom function with a pre-chosen keyword/password, let's say "Mellon" (not case-sensitive if possible).
i'll explain myself better.
Let's say i'm gonna write "Mellon fellas" in the TextArea inside the Chat Log, my idea is to simply trigger the JoinedInTheRoom function by the fact that "Mellon", the keyword, has been just sent inside the messagge, i hope that my intent it's clear.
Thanks in advance.
here is the code:
HTML - CHAT LOG + TEXT AREA AND BUTTON
<!-- CHAT LOG -->
<h3>Chat Log</h3>
<div class="ChatLog">
<div class="msg left-msg">
<div class="msg-img" style="background-image: url()"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">System</div>
</div>
<div class="msg-text">Write the Keyword to join the room and unlock the NPCs and Quests</div>
</div>
</div>
</div>
<!-- TEXT AREA AND BUTTON -->
<form class="FormInputArea">
<textarea class="InputCamp" id="TextArea" placeholder="Explain your move in max 200 characters..." required></textarea>
<button class="button" type="submit" id="SendButton"> Send </button>
</form>
JAVA SCRIPT - CHAT LOG + TEXT AREA AND BUTTON
// CHAT LOG + TEXT AREA AND BUTTON
const ChatLog = get(".ChatLog");
const FormInputArea = get(".FormInputArea");
const InputCamp = get(".InputCamp");
JAVA SCRIPT - JoinedInTheRoom + NpcsUnlocked
// JoinedInTheRoom + NpcsUnlocked
function JoinedInTheRoom(side) {
const NpcsUnlocked = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">You've joined the room, feel free to choose your quest.</div>
</div>
</div>
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${BOT_IMG})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${BOT_NAME}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">
<p onclick="Npc1('RANDOM TASK DESCRIPTION 1')"> Npc 1. </p>
<p onclick="Npc2('RANDOM TASK DESCRIPTION 2')"> Npc 2. </p>
</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", NpcsUnlocked);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const NpcsUnlocked = InputCamp.value;
if (!NpcsUnlocked) return;
const Delay = NpcsUnlocked.split(" ").length * 600;
setTimeout(() => {
JoinedInTheRoom("left", NpcsUnlocked);
InputCamp.value = " ";
}, Delay);
})
JAVA SCRIPT - PLAYER MESSAGE SCRIPT
// PLAYER MESSAGE SCRIPT
function AppendMessage(name, img, side, text) {
const msgHTML = `
<div class="msg ${side}-msg">
<div class="msg-img" style="background-image: url(${img})"></div>
<div class="msg-bubble">
<div class="msg-info">
<div class="msg-info-name">${name}</div>
<div class="msg-info-time">${formatDate(new Date())}</div>
</div>
<div class="msg-text">${text}</div>
</div>
</div>
`;
ChatLog.insertAdjacentHTML("beforeend", msgHTML);
ChatLog.scrollTop += 500;
}
FormInputArea.addEventListener("submit", event => {
event.preventDefault();
const msgText = InputCamp.value;
if (!msgText) return;
AppendMessage(PERSON_NAME, PERSON_IMG, "right", msgText);
InputCamp.value = "";
});
Searching on internet i found this 11 years old stackoverflow post that i think it might help me, it seems i might use "indexOf" for this job, i'm right ? Maybe you guys can help me make it a little bit more "modern" and apply it to my code ?
Link
You could use the .includes function, like below
if (msgText.includes("mellon")) {
JoinedInTheRoom();
}
It'll search the whole string and return true if "mellon" is found. However it will also return true if someone types a word containing mellon. "smellon" or "smellonies" would return true and run the JoinedInTheRoom function too
When a user creates a product, I want that product to be broadcasted to all other users and dynamically added to their screens. So far the broadcast aspect works amazingly.
But how can I dynamically add in this '.product' class, as well as all of a nested divs in an easy way? At the moment the only thing I can think of is copying and pasting all of it's divs in a jquery variable and adding it that way- there must be an easier way.
Here is where products are first loaded in when the page loads
<div class="product" id="{{$product->id}}">
<div class="product-image"><img src="/imgs/products/{{$product->type_id}}.png"></div>
<div class="product-content">
<div class="product-title" id="product-title">
{{ strtoupper(\App\ProductType::where('id', $product->type_id)->first()->name)}}
</div>
<div class="product-price">PRICE PER UNIT: <div class="price-value" id="price">{{$product->price}}</div> EXENS</div>
<br/>
QUANTITY: <div class="quantity-value" id="quantity">{{$product->quantity_available}}</div>
#if(strpos(\App\Group::where('id', $player->group_id)->first()->options, "\"showName\":true") !== false)
<br/>
SELLER: <div class="seller" id="seller">{{\App\User::where('id',$product->seller_id)->first()->name}}</div>
#endif
<br/>
PRICE: <div class="total-price" id="total-price">{{$product->price * $product->quantity_available}}</div>
<form class="buy-product-form" action="/UoE/buy-product/{{$product->id}}" method="POST">
{{csrf_field()}}
<button class="pull-right btn btn-primary">BUY NOW</button>
</form>
</div>
</div>
When the event is received the only way I can think of doing it as:
var productToAdd="<div class='buy-product-form'><div id='price'></div> " +
"" +
"" + //insert a massive string here containing all the other aforementioned sub-divs
"" + //And populate with json data
"" +
"</div>";
$('.content').append(productToAdd);
My solution was to take the entire code posted in the question and do make it as a one big HTML tag. That way my JS function can append the page with a HTML product div and it will already be bound with the necessary event listeners.
I'm trying to select the next element to add the class image-radio-selected with JQuery.
My html is like
<div id="photocall">
#foreach ($photocalls as $photocall)
<div class="d-inline-block mx-1">
<div style="background-image: url('')" class="photocallThumb image-radio-selected"></div>
</div>
#endforeach
<input>
</div>
Im trying to:
$( "#mybutton" ).on("click", function() {
var selected = $('.photocallThumb.image-radio-selected'); // working
selected.next('.photocallThumb').addClass('image-radio-selected'); // not working
});
After 2 hours, trying to solve, reading doc,
I'm more confused than when I started...
what am I doing wrong?
One method is you will need to get out of the parent div, then do a next for the parent.
$( "#mybutton" ).on("click", function() {
var selected = $('.photocallThumb.image-radio-selected');
selected.parent(".d-inline-block").next(".d-inline-block").find('.photocallThumb').addClass('image-radio-selected'); // not working
});
.image-radio-selected{border:1px solid #ff00aa;}
.mx-1{width:100px;height:100px;border:1px solid #000000;}
.d-inline-block{display:inline-block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="photocall">
<div class="d-inline-block mx-1">
<div style="background-image: url('')" class="photocallThumb image-radio-selected"></div>
</div>
<div class="d-inline-block mx-1">
<div style="background-image: url('')" class="photocallThumb"></div>
</div>
<div class="d-inline-block mx-1">
<div style="background-image: url('')" class="photocallThumb"></div>
</div>
<div class="d-inline-block mx-1">
<div style="background-image: url('')" class="photocallThumb"></div>
</div>
<button type="button" id="mybutton">next</button>
</div>
JQuery's next method selects the next sibling of the selected element. However, since your photocallThumb div is inside a d-inline-block div, it has no siblings. You'd have to go back up a level, then find the next photocallThumb, maybe something like selected.parent().find('.photocallThumb').eq(0).
However, an even better pattern that will help you avoid bugs like these is called templating. Basically, on the client side, you have an html template string, and you pass it data that represent your current state. In your case, you'd pass it an array of javascript objects, each one with an image url and an isSelected boolean. Then, when your state changes, instead of using jquery to try to fix what's changed, you just rerender your template and replace your html element's content with the newly rendered template, and it's now magically in the correct state. This is the pattern favored by large frameworks like React and Angular.
Here's an example from lodash that renders a list of usernames:
// Use the "evaluate" delimiter to execute JavaScript and generate HTML.
var compiled = _.template(
`<% _.forEach(users, function(user) { %>
<li><%- user %></li>
<% }); %>`);
compiled({ 'users': ['fred', 'barney'] });
// => '<li>fred</li><li>barney</li>'
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'p#p_50\')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
JQuery/JS:
function quote(post) { $(post).text(); }
This works to fetch the posts message, but how do I go about finding the Username?
I have tried using $(post).prev('a').text();, and $(post).parent().prev('a').text();, but nothing seems to work.
You can do it without jQuery. If possible, change the html and pass the current link to the function, like this:
<a onclick="quote(\'p#p_50\', this)">Quote</a>
Then you can just search through all links:
function quote(str, currentLink) {
var allLinks = document.getElementsByTagName("a"); // get all links in document
var index = allLinks.indexOf(currentLink);
if (index > 0) {
var prevLink = allLinks[index-1];
console.log(prevLink); // log it to browser console
} else {
console.log("there is no previous link");
}
}
By looking at the DOM structure, it should work with $(post).parent().prev().text().
Alternative way, how about you wrap all of them with <div>, like this: XD
<div id="message1">
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote(\'#message1\')">Quote</a> //change to wrapper id
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
</div>
then to get the post text: $(post).find('#p_50').text();
to get the username: $(post).find('a:first').text();
Looking at your sample HTML, if you're at p, just go to parent element and get the closest a and you should be fine:
function quote(post) {
var post = $(post).text();
var user = $(post).parent().closest('a').text();
}
Perhaps using parent() and then previous()
var ancortext = $(post).parent().prev().text();
A function example below.
function username(post) {
return $(post).parent().prev().text();
}
Note: This smells to me, your code is very much tied into the structure of the HTML this way. If you alter the HTML, chances are your javascript will break.
I have copied your code into my own HTML document, and confirmed that the jquery method calls above output the desired result. If you are not, then something is different with your source HTML and the source that you posted, or your jquery functions differ from the ones stated in this answer :)
your onclick attribute is wrong,because onclick accept javascript,so the value could be support js,then onclick="quote('p#p50')".
function quote(post) {
var subject = $(post).text();
var user=$(post).parent().prev('a').text();
console.log('posted '+subject+' by '+user);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SOMEUSERNAME
<div class="col s9">
<p id="p_50">Some message</p>
<br>
<br>
<span class="forumtools">
<strong>
<a onclick="quote('p#p_50')">Quote</a>
</strong>
<span class="right">Written SOMEDATE</span>
</span>
</div>
i m working on adding a FB share button to all my posts.
so i wanted to use the sharer.php? method with all the parameter retrieved from the post.
So my blog structure
<div id='postwrapper'>
<div id='title'>
hello</a>
</div>
<div id='da'>
<span>Posted on </span>
<span class='divider'></span>
<span>By</span>
</div>
<div class='post_content'>$row['post'] gud day</div>
<div id='post_footer'>
<a href=viewpost.php>Continue reading</a>
<a href='#' onClick='fbshare(this)'>Insert text or an image here.</a>
</div>
</div>
My javascript for fbshare function (not complete).
function fbshare(fb) {
var p1 = fb.parentNode;
var p2 = p1.parentNode;
var title = p2.getElementById("title").innerHTML;
alert(title);
}
Everytime i try this it says undefined is not a function
getElementById is a function of the document. Assuming you have more than one post on the page (ids must by unique), try using a class instead:
<div class='title'>
And using getElementsByClassName:
var title = p2.getElementsByClassName("title")[0].innerHTML;
http://jsfiddle.net/AJ9uj/