Getting parent element javascript - javascript

I have a bit of a problem which i just can't get my head round, i could but it would just be defeating the whole purpose of getting better. So with that being said i have set of elements which all have the same class name and when i select a button i want it to only get me the elements within that parent that is clicked.
<article class="col-xs-12 col-sm-3">
<a href="http://79.170.43.200/shaveandsubscribe2.co.uk/shaveandsubscribe2/index.php/gillette-fusion-proshield.html?___SID=U">
<h3>Gillette Fusion ProShield</h3>
<pid class="temp_pid" style="display:none;">366730415</pid>
<pid2 class="temp_pid" style="display:none;">373545146</pid2>
<pid3 class="temp_pid" style="display:none;">373546370</pid3>
<img src="http://79.170.43.200/shaveandsubscribe2.co.uk/shaveandsubscribe2/media/catalog/product/cache/1/image/265x/9df78eab33525d08d6e5fb8d27136e95/g/i/gillette-fusion-proshield.jpg" alt="Gillette Fusion ProShield" class="img-responsive">
</a>
<div class="1" style="display:none;">
<button type="button" id="1" title="Proceed" class="button btn-cart" onclick="getUrl(this.id);"><span><span>Proceed</span></span></button>
<input type="hidden" id="x1" class="rrp_price" name="rrp_price" value="$19.4900">
<input type="hidden" id="y1" class="spcl_price" name="spcl_price" value="$19.4900">
</div>
<button class="price-change" id="1" value="£19.49" name="£19.49" onclick="getSet(this.id);">Select</button>
</article>
the class i am trying to get is "temp_pid" now i have the code above there is effectively 3 lots of that at the minute my script get's all of the temp_pid classes which in total is 9.
jQuery('body').on('click','.price-change',function(){
localStorage.removeItem('priceChange');
localStorage.setItem('priceChange', "priceChange");
// alert(localStorage.getItem("priceChange"));
// cratejoy script to capture product ids aka <pid> etc...
if(jQuery('.price-change').hasClass('selected')){
var x = document.getElementsByClassName('temp_pid');
for(var i = 0; i < x.length; i ++){
console.log(x[i].innerHTML);
}
};
});

Try data-id.It will select the element within the parent.I hope it will work

Related

How to retrieve shopping cart items, implementing LocalStorage

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

How to set value (same value) to all elements of the same id? Javascript

How can I get through javascript all the elements of the same id and apply the same value to all of them?
Below is my form. It's a loop that creates 71 subdivs and every one of them contain a specific button image and hidden inputs. Every one of the inputs it's supposed to have the same name and id as the other 70.
If I make the input visible and put $i as a value , when page loads it shows everything correct. 71 images with 71 different values. Although if I submit that way I alwats get the same value on my controller no matter the image I choose to click on.
So I want to add to my onMouseOver function a way to set the current value of the hovered image to all the inputs. That way if I click on image to submit the value would have been set correct.
My form:
<form action="/searches/se_racestandingsround" method="post">#csrf
<div class="row mt-5 mr-5 ml-5">
<?php for($i=2021; $i>=1950; $i--){ ?>
<div class="col-3 d-flex flex-column align-items-center mb-3 mt-5">
<div class="w-50 mb-5 rounded-circle" style="height: 150px;">
<div class="bg-dark w-100 h-100 mb-5 border rounded-circle toClick" id="<?php echo $i ?>" onmouseover="onMouseOver(this)" onmouseout="onMouseOut(this)">
<input type="hidden" name="round" id="round">
<input type="hidden" name="rnd" id="rnd">
<button style="object-fit:cover" class="w-100 h-100 border rounded-circle"><img src='/imgs/jpg/years/<?php echo $i ?>.jpg' style="object-fit:cover" class="w-100 h-100 border rounded-circle"></button>
</div>
</div>
</div>
<?php } ?>
</div>
</form>
My onMouseOver function:
function onMouseOver(year){
// alert("Hello! I am an alert box!!");
var curYear = year.id;
// document.getElementById('rnd').value = currentNumOfRounds; //NOT WORKING
// document.getElementById('round').value = curYear; //NOT WORKING
}
If you insist on using one id for multiple elements, then your only option is to use querySelectorAll:
setTimeout(() => {
document.querySelectorAll("#a").forEach(v => {
v.innerText = "what";
})
}, 3000);
<p id="a">one</p>
<p id="a">two</p>
<p id="a">three</p>
<p id="a">four</p>
But you really should be using classes instead.
all the elements of the same id an ID has to be unique within the document.
Having that said you theoretically could query for all elements with the same value for the id attribute using the attribute selector.
function setAllElementsTo(value) {
document.querySelectorAll('[id="a"]').forEach(element => {
element.value = value
})
}
setAllElementsTo('a');
<input id="a">
<input id="a">
<input id="a">
<input id="a">
<input id="a">
This works but does not change the fact that the document is semantically incorrect.
Instead, you should use different IDs and use something else that those elements have in common. Like a class, a data- attribute or what ever else makes sense.
To further the explanations, IDs are meant to be unique and only appear once on a page. This helps people who use screen readers and keeps your javascript clean. JS assumes you only have one instance of an ID on a page, so it will only return the first instance of it, which is likely why you always get the same value in your controller.
However, you should be able to use a Class instead to achieve what you're trying to do.

How to proper positioning elements in jQuery Mobile?

I want to have in listview in listitem (Note: the listitem <li> is generated dynamically with JS) product value on the left and button on the right but
I have align="center" in <div data-role="main" align="center">
and get centered product value and button but if I place in <div> (in listitem) product value and in another <div> a button
I get on the left product value and on the right button (but in lower line)
like this img
so how to proper position this?
var li = '<li><div>' + productVal + btn + '</div></li>';
so on the left sth and on the right a button
here is my code https://jsbin.com/revuto/edit?html,output
actually I have
but want
sorry for Polish text in code
so I translate Polish - English
Wprowadź product - provide a product
dodaj - add
usuń- remove
niebezpieczna strefa- danger zone
use a wrapper classed ui-grid-a and wrap each "column" in a div ui-block-a and ui-block-b
e.g.
<div class="ui-grid-a">
<label class="ui-block-a" for="input">
label: <input type="text" id="input">
</div>
<div class="ui-block-b">
<br>
<button type="button" >Button</button>
</div>
</div>

Making div contents persistant

I have an interesting problem, which I would like some help with if possible.
I have the following segments of HTML:
<div id="main_">
<ul class="unstyled">
<ui:repeat var="adultPassenger" varStatus="adult" value="#{bean.adultPassengers}">
<li>
<div id="adult#{adult.index}" class="hitbox_">
<div id="passengerTitle">Adult #{passengerDetailsBean.getPassengerCount(adult.index)}</div>
</div>
<div class="hide">
<div id="adult#{adult.index}_form">
<div>
<div>
<div class="pull-left" style="width: 50%;">
<div><h:inputText value="#{adultPassenger.firstName}" class="pasFirstName_adult#{adult.index}" label="First Name"></h:inputText></div>
</div>
<div class="button-container">
<h:commandButton value="Continue" styleClass="btn btn-warning btn-large btn-block" onclick="handleDetailsClick('adult#{adult.index}')"></h:commandButton>
</div>
</div>
</div>
</div>
</div>
</li>
</ui:repeat>
</ul>
</div>
and
<div id="secondary_" class="hide">
<table>
<tbody>
<tr>
<td">
<h:commandButton id="secondaryBack" value="Back" styleClass="btn btn-warning">
</h:commandButton>
</td>
<td class="secondaryTitle">
<h3 class="page-title orange-title-big">Passenger Details</h3>
</td>
</tr>
</tbody>
</table>
<div id="secondaryContents">
</div>
</div>
They're both on the same page, and when the one div is visible the other is invisible. Thing is. Here's the JS I'm currently using:
$(".hitbox_").click(function() {
var round = Math.round;
var id = $(this).attr("id");
window.alert(id);
var f = $("pasFirstName_"+id).get();
console.log("name " + f.value);
// set contents of secondary div
var passengerDetails = $("#" + id + "_form").html();
$("#secondaryContents").html(passengerDetails);
$("#main_").toggleClass("hide");
$("#secondary_").toggleClass("hide");
});
function handleDetailsClick(index) {
var passengerDetails = $("#" + index + "_form").html();
$("#secondaryContents").html(passengerDetails);
$("#main_").toggleClass("hide");
$("#secondary_").toggleClass("hide");
}
What I want(and have tried, unsuccessfully, to achieve):
When the first div is clicked, it is hidden and the second div is shown after being populated with the hidden form in the first div. I do this to preserve class names etc, since there could be more than one such form.
When "Continue" is clicked, the second div is hidden, and it's contents passed back to the first div - I do this to preserve the details that were entered on the form.
My problem is that the details don't persist. When the same div is clicked again after having filled in the form before, it should should the form with the details that were previously entered.
This is where something goes wrong because there are never details in the form.
Does anyone know what I could be doing wrong?
The problem is in the following lines
var passengerDetails = $("#" + id + "_form").html();
$("#secondaryContents").html(passengerDetails);
Here, you are taking HTML of one div and adding it to another. While this will surely create the same html in target div, it will not retain any user entered values as well as any events bound on elements.
You should, instead, take the element and append it to target
var passengerDetails = $("#" + id + "_form").children();
$("#secondaryContents").append(passengerDetails);

jQuery selector trouble

I have a bunch of smilies in a page, which on click has to be selected. I tried implementing a jquery based solution but am stuck at this stage, where multiple smilies are getting selected :
<div class="smiles_feed">
<input type="text" id="rating" value="" name="rating" class="displaynone" />
<div style="float:left;width:auto;text-align:Center;">
<button type="button" class="awesomesmile" class="unselected" value="Awesome" style="margin-bottom:0px;"></button>
<div class="smiletitle" style="font-size:9pt;color:white;">Yummy!</div>
</div>
<div style="float:left;width:auto;text-align:Center;">
<button type="button" class="goodsmile" class="unselected" value="Good" style="margin-bottom:0px;"></button>
<div class="smiletitle" style="font-size:9pt;color:white;">Good!</div>
</div>
<div style="float:left;width:auto;text-align:Center;">
<button type="button" class="okaysmile" class="unselected" value="Okay" style="margin-bottom:0px;"></button>
<div class="smiletitle" style="font-size:9pt;color:white;">Okay!</div>
</div>
<div style="float:left;width:auto;text-align:Center;">
<button type="button" class="yucksmile" class="unselected" value="Yuck" style="margin-bottom:0px;"></button>
<div class="smiletitle" style="font-size:9pt;color:white;">Yuck!</div>
</div>
</div>
<script type='text/javascript'>
$(function(){
// Smile Click Function
$('div.smiles_feed :button').click(function(){
$(this).removeClass('unselected').addClass('selected');
$(this).siblings().removeClass('selected').addClass('unselected');
$('#rating').val($(this).val());
//alert($('#rating').val());
});
});
</script>
What am I doing wrong? How do I change the javascript function to make it select only one smiley?
$(this) inside your click() function refers to the button that was clicked, not the div that was clicked. You need to add the selected class to $(this).parent().
The elements returned by siblings() are not the divs that represent other smileys, but rather are other elements of this smiley (in this case, div.smiletitle).
To get a list of the other smileys, you should be looking at $(this).parent().siblings().
If your button is what represents the smiley, then you should be traversing other smileys like this:
$(this).parent().siblings().children('button')
and making them each get deselected:
$(this).parent().siblings().children('button').each(function(){
$(this).removeClass('selected')
.addClass('deselected');
});

Categories