Increment a random number with a button? - javascript

I'm new to coding and I have the following problem:
I created a random number and I have it in a p tag which has a class, then I tried to increment this number by clicking on a button. This is my code so far:
$(document).ready(function(){
let films = JSON.parse(movies);
for (let i = 0; i < films.length; i++){
let movie = `
<div class="container">
<div class="poster">
<img class="pic" src="${films[i].image}">
</div>
<div class="text-box">
<div class="details">
<h2>${films[i].title}</h2>
<p>${films[i].releaseDate}</p>
<p>Genre: ${films[i].genre}</p>
<p>Director: ${films[i].director}</p>
</div>
<div class="like-box">
<input type="button" class="btn" value="Like 👍" number="${i}"></input>
<p class="counter"></p>
</div>
</div>
</div>
`;
$("#main2").append(movie);
$(".counter").text(Math.floor((Math.random()*100) + 1));
}
$(".btn").click(function() {
let el = parseInt($(".counter").text());
$(".counter").text(el+1);
})
});
The problem is, that if I click on the button instead of getting for example: 19 then after the click 20, what I get is 191919191920. So basically the button works, but not exactly how I want it to work. Can anybody help me please?

for (let i = 0; i < films.length; i++){
after this for loop is done, there will be films.length elements in dom with class counter.
and what this $(".counter").text() will return is concatenation of all text in elements with classes counter. That's why you got 191919191920.

Changes you would need to do:
Add new class to the container increaseing row count. This is mandatory to identify which movie you're on and increase the like value.
<div class='container row-" +i+ "'">
Then add onClick event to the like button to pass which row you're on. This is to identify which counter to increase the value.
<input type="button" class="btn" value="Like 👍" number="1" onclick="incrementLikes('row-" +i+ "')"></input>
$(document).ready(function() {
$(".counter").text(Math.floor((Math.random() * 100) + 1));
});
function incrementLikes(rowId) {
let mainRow = document.getElementsByClassName(rowId)[0];
let counter = parseInt(mainRow.getElementsByClassName('counter')[0].innerHTML);
mainRow.getElementsByClassName('counter')[0].innerHTML = counter + 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container row-1">
<div class="poster">
<img class="pic" src="">
</div>
<div class="text-box">
<div class="details">
<h2>Film Title 1</h2>
<p>13/06/2020</p>
<p>Genre: Action</p>
<p>Director: John Doe</p>
</div>
<div class="like-box">
<input type="button" class="btn" value="Like 👍" number="1" onclick="incrementLikes('row-1')"></input>
<p class="counter"></p>
</div>
</div>
</div>
<div class="container row-2">
<div class="poster">
<img class="pic" src="">
</div>
<div class="text-box">
<div class="details">
<h2>Film Title 2</h2>
<p>13/06/2020</p>
<p>Genre: Action</p>
<p>Director: John Doe</p>
</div>
<div class="like-box">
<input type="button" class="btn" value="Like 👍" number="1" onclick="incrementLikes('row-2')"></input>
<p class="counter"></p>
</div>
</div>
</div>
<div class="container row-3">
<div class="poster">
<img class="pic" src="">
</div>
<div class="text-box">
<div class="details">
<h2>Film Title 3</h2>
<p>13/06/2020</p>
<p>Genre: Action</p>
<p>Director: John Doe</p>
</div>
<div class="like-box">
<input type="button" class="btn" value="Like 👍" number="1" onclick="incrementLikes('row-3')"></input>
<p class="counter"></p>
</div>
</div>
</div>

The problem is your selector ".counter"
$(".counter").text returns the combined string value of all elements that have the class ".counter"
I have modified your code using selectors specific to the clicked button
let films = JSON.parse(movies);
for (let i = 0; i < films.length; i++){
let buttonId = "button" + i;
let movie = `
<div class="container">
<div class="poster">
<img class="pic" src="${films[i].image}">
</div>
<div class="text-box">
<div class="details">
<h2>${films[i].title}</h2>
<p>${films[i].releaseDate}</p>
<p>Genre: ${films[i].genre}</p>
<p>Director: ${films[i].director}</p>
</div>
<div class="like-box">
<input id="${buttonId}" type="button" class="btn" value="Like 👍" number="${i}"></input>
<p class="counter"></p>
</div>
</div>
</div>
`;
$("#main2").append(movie);
$("#${buttonId}.btn").next().text(Math.floor((Math.random()*100) + 1));
}
$("#${buttonId}.btn").click(function() {
let el = parseInt($("#${buttonId}.btn").next().text());
$("#${buttonId}.btn").next().text(el+1);
})

Related

Search form with 2 input fields with different filterable classes upon search

I have this code to filter out text div's upon search.
The first input would filter out by the 'name' & 'sku' classes. The second would then filter out by 'location'.
When trying to filter by location it would display all divs with the searched location, but I need it to correlate to the first inputs search. I also need to add a button that would carry out the search function once clicked instead of having it automatically filter out upon search.
I would then also need them to sort price lowest to highest by means of a dropdown but I have no idea on how to get this done.
Could someone please assist.
$(document).ready(function() {
var $btns = $('.btn').click(function() {
if (this.id == 'all') {
$('#parent > div').fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
$('#parent > div').not($el).hide();
}
$btns.removeClass('active');
$(this).addClass('active');
})
var $search = $("#search").on('input', function() {
$btns.removeClass('active');
let value = $(this).val();
$('.box').show().not(function() {
return new RegExp(value, 'gi').test($(this).find('.name, .sku').text());
}).hide();
});
var $search = $("#search-location").on('input', function() {
$btns.removeClass('active');
let value = $(this).val();
$('.box').show().not(function() {
return new RegExp(value, 'gi').test($(this).find('.location').text());
}).hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input type="text" id="search" class="form-control" placeholder="Search product by name or sku">
<input type="text" id="search-location" class="form-control" placeholder="Search product by location">
</div>
</div>
<hr>
<div class="row" id="parent">
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Pepsi </p>
<p class="sku">D-1251</p>
<p>$ 2,410</p>
<p class="location">east</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Cocacola </p>
<p class="sku">D-1314</p>
<p>$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Mountien Dwe </p>
<p class="sku">D-458</p>
<p>$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Burger </p>
<p class="sku">F-125</p>
<p>$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog </p>
<p class="sku">F-7412</p>
<p>$ 2,410</p>
<p class="location">south</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2</p>
<p class="sku">F-74122</p>
<p>$ 2,4105</p>
<p class="location">east</p>
</center>
</div>
<div class="col-md-2 box location-box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2233</p>
<p class="sku">F-74112</p>
<p>$ 2,4103</p>
<p class="location">north</p>
</center>
</div>
</div>
At first you should mark divs with adding "someAdditionalClass" then remove "someAdditionalClass" which is not found in text filter, when you search by name or sku.
then when you search after filter, you should search by box.someAdditionalClass. here is your working code.
var $search = $("#search").on("input", function () {
$btns.removeClass("active");
let value = $(this).val();
$(".box")
.show()
.addClass("someAdditionalClass")
.not(function () {
return new RegExp(value, "gi").test(
$(this).find(".name, .sku").text()
);
})
.removeClass("someAdditionalClass")
.hide();
});
var $search = $("#search-location").on("input", function () {
$btns.removeClass("active");
let value = $(this).val();
$(".box.someAdditionalClass")
.show()
.not(function () {
return new RegExp(value, "gi").test(
$(this).find(".location").text()
);
})
.hide();
});
working example on jsfiddle:
https://jsfiddle.net/zaLd08h5/
I also added your missing buttons :)
The problem with your code is that you are applying the filter on the .box class for each search field. So the typing on the 2nd field was overriding the results.
My assumption is you want to search the results matching either name/sku AND location. In case you meant OR condition, you just need to change the logic a bit.
Searching on typing is more intuitive, but if you really need the search button, then your code should become simpler. You don't need to implement .on() for each search input.
Also, added the logic for the sort. However, it would recommend sorting the result on the input data set. I am sure you are generating the list from some javascript variable which would be populated via some api call or data fetch function. With the current functionality, the sort will only be applied upon sorting, the initial data may not be sorted.
var elems;
$(document).ready(function () {
elems = $(".drink, .food");
});
function search() {
let nameSkuVal = $("#search").val().toLowerCase();
let locVal = $("#search-location").val().toLowerCase();
var finalElems = elems.filter(function () {
name = $(this).find(".name").text().toLowerCase();
sku = $(this).find(".sku").text().toLowerCase();
loc = $(this).find(".location").text().toLowerCase();
return (nameSkuVal ? name.includes(nameSkuVal) || sku.includes(nameSkuVal) : true) && (locVal ? loc.includes(locVal) : true);
}).sort(function (a, b) {
n1 = parseFloat($(a).find(".price").text().replace("$ ", "").replace(",", ""));
n2 = parseFloat($(b).find(".price").text().replace("$ ", "").replace(",", ""));
return (n1 < n2) ? -1 : (n1 > n2) ? 1 : 0;
});
$('#parent').html(finalElems);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-4">
<input type="text" id="search" class="form-control" placeholder="Search product by name or sku">
<input type="text" id="search-location" class="form-control" placeholder="Search product by location">
<button onclick="search()">Search</button>
</div>
</div>
<hr>
<div class="row" id="parent">
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Pepsi </p>
<p class="sku">D-1251</p>
<p class="price">$ 2,415</p>
<p class="location">east</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Cocacola </p>
<p class="sku">D-1314</p>
<p class="price">$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box drink">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Mountien Dwe </p>
<p class="sku">D-458</p>
<p class="price">$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Burger </p>
<p class="sku">F-125</p>
<p class="price">$ 2,410</p>
<p class="location">north</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog </p>
<p class="sku">F-7412</p>
<p class="price">$ 2,410</p>
<p class="location">south</p>
</center>
</div>
<div class="col-md-2 box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2</p>
<p class="sku">F-74122</p>
<p class="price">$ 2,4105</p>
<p class="location">east</p>
</center>
</div>
<div class="col-md-2 box location-box food">
<center>
<img src="http://via.placeholder.com/80x80" class="" alt="">
<p class="name">Hot Dog 2233</p>
<p class="sku">F-74112</p>
<p class="price">$ 2,4103</p>
<p class="location">north</p>
</center>
</div>
</div>

How to get Parent element

I'm trying to get the parent element of cartError so I can access the particular cart-item-details where the cart-item-size and itm-quantity is... because I'm looping through the cart to if a new cart item is added with the same size increase quantity from 1 to 2
var cartItems = document.getElementsByClassName('side-cart- items')[0]
var cartItemSizes = cartItems.getElementsByClassName("cart-item-size")
for(var i=0; i < cartItemSizes.length;i++){
cartError=cartItemSizes[i]
if(cartError.innerText== size){
var cartItem = cartError.parentElement
var cartQuantity = cartError.getElementsByClassName('itm-quantity')
console.log(cartQuantity.innerText)
return
}
}
<div class="section side-cart-items">
<div class="side-cart-item">
<div class="cart-item-image">
<img src="./images/product/SASSI-HOLFORD-RTW-SS21-AQUAREMARINE-PEARL-DUNSTER-TOP-DUNSTER-SHORTS-2-1154x1600.jpg" alt="">
</div>
<div class="cart-item column">
<div class="cart-item-details">
<h2>Dunster Shorts</h2>
<p>size <span class="cart-item-size">36</span></p>
<p><span class="itm-quantity">1 </span>×<span class="itm-price">$285.00</span></p>
</div>
<button class="cart-item-remove">[ REMOVE ]</button>
</div>
</div>
<div class="side-cart-item">
<div class="cart-item-image">
<img src="./images/product/SASSI-HOLFORD-RTW-SS21-AQUAREMARINE-PEARL-DUNSTER-TOP-DUNSTER-SHORTS-2-1154x1600.jpg" alt="">
</div>
<div class="cart-item column">
<div class="cart-item-details">
<h2>Dunster Shorts</h2>
<p>size <span class="cart-item-size">40</span></p>
<p><span class="itm-quantity">1</span> ×<span class="itm-price">$200.00</span></p>
</div>
<button class="cart-item-remove">[ REMOVE ]</button>
</div>
</div>
</div>
Note that parent element of cartError is p tag not cart-item-details. Actually you need to use cartError.parentElement.parentElement to access the cart-item-details and then use cartItem.getElementsByClassName('itm-quantity'); to access the all itm-quantity tags:
var size = "36";
var cartItems = document.getElementsByClassName('side-cart-items')[0]
var cartItemSizes = cartItems.getElementsByClassName("cart-item-size");
for (var i = 0; i < cartItemSizes.length; i++) {
cartError = cartItemSizes[i]
if (cartError.innerText == size) {
var cartItem = cartError.parentElement.parentElement
var cartQuantity = cartItem.getElementsByClassName('itm-quantity');
for (let item of cartQuantity) {
console.log(item.innerText);
}
}
}
<div class="section side-cart-items">
<div class="side-cart-item">
<div class="cart-item-image">
<img src="./images/product/SASSI-HOLFORD-RTW-SS21-AQUAREMARINE-PEARL-DUNSTER-TOP-DUNSTER-SHORTS-2-1154x1600.jpg" alt="">
</div>
<div class="cart-item column">
<div class="cart-item-details">
<h2>Dunster Shorts</h2>
<p>size <span class="cart-item-size">36</span></p>
<p><span class="itm-quantity">1 </span>×<span class="itm-price">$285.00</span></p>
</div>
<button class="cart-item-remove">[ REMOVE ]</button>
</div>
</div>
<div class="side-cart-item">
<div class="cart-item-image">
<img src="./images/product/SASSI-HOLFORD-RTW-SS21-AQUAREMARINE-PEARL-DUNSTER-TOP-DUNSTER-SHORTS-2-1154x1600.jpg" alt="">
</div>
<div class="cart-item column">
<div class="cart-item-details">
<h2>Dunster Shorts</h2>
<p>size <span class="cart-item-size">40</span></p>
<p><span class="itm-quantity">1</span> ×<span class="itm-price">$200.00</span></p>
</div>
<button class="cart-item-remove">[ REMOVE ]</button>
</div>
</div>
</div>

Javascript faceted search

I have this page I'm working on, I'm trying to make a facted search for it. (only issue is I have no json as I'm looping through via django.)
What I currently have is this:
var wood = []
$(".checkbar").click(function() {
id = this.id
$('.spe_' + id).toggleClass("filteredlabel");
$('.flr').addClass("hide");
$('.flr_spe_' + id).removeClass("flr hide").addClass("flrcheck");
if (this.classList[1] == 'checked') {
if (wood.length > 0) {
debugger;
$('.flr_spe_' + this.id).removeClass("hide").addClass("flr");
for (var i = 0; i < wood.length; i++)
if (wood[i] === this.id) {
if (wood.length > 1) {
$('.flr_spe_' + this.id).addClass("hide");
}
if (wood.length == 1) {
$('.flr').removeClass("hide");
}
wood.splice(i, 1);
break;
}
}
$(this).toggleClass("checked");
} else {
$(this).toggleClass("checked");
wood.push(this.id)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbar" id="1">
<div class="row">
<div class="box"></div>
<div class="tick"><i class="fas fa-check"></i></div>
Oak (1)
</div>
</div>
<div class="checkbar" id="2">
<div class="row">
<div class="box"></div>
<div class="tick"><i class="fas fa-check"></i></div>
Pine (1)
</div>
</div>
<div class="col-md-4 flr flr_spe_1 flr_rg_1">
<div class="card">
<div class="card-body" align="center">
<div class="flrimagecontainer">
<img class="flrimg" src="/media/images/wood/st_tobacco2x.png" alt="Logo" />
<div class="flrafter">
<p class="spectitle">SPECIES</p>
<p class="spec">Oak</p>
<p class="spectitle">RANGE</p>
<p class="spec">Old Wood</p>
<p class="spectitle">STYLE</p>
<p class="spec">Herringbone</p>
<p class="spectitle">TEXTURE</p>
<p class="spec">Prme</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4 flr flr_spe_2 flr_rg_1">
<div class="card">
<div class="card-body" align="center">
<div class="flrimagecontainer">
<img class="flrimg" src="/media/images/wood/straightwood_CfuTJb4.png" alt="Logo" />
<div class="flrafter">
<p class="spectitle">SPECIES</p>
<p class="spec">Pine</p>
<p class="spectitle">RANGE</p>
<p class="spec">Old Wood</p>
<p class="spectitle">STYLE</p>
<p class="spec">Herringbone</p>
<p class="spectitle">TEXTURE</p>
<p class="spec">Prme</p>
</div>
</div>
</div>
</div>
</div>
The problem is when I have to start adding more checkboxes to filter on. If i add another set of checkboxes for range, how would I go about making this so that they filter correctly together?
e.g. if I check Old Wood, And then Check Pine, How can I get just the results that have "Old Wood" and "Pine" and not return Oak?
Many Thanks

Hide parent div class if child div class does not have content when there are multiple parent divs with the same class name

I have a slider where some of the images in the slider can have an optional photo- credit containing text or link in a popper. I would like to iterate over all of the popper instances and if all of the p tags in the .photo-credit p class are empty, then hide only that instance of the parent popper. I've tried to piece together a solution from some other posts, but have not been able to get it to work. The code I have does not hide a popper if all p tags are empty for that popper. I'm a JavaScript newbie and would appreciate any help.
HTML
<div class="slider-wrapper">
<!--Required Root Element-->
<div class="slider">
<!--Required List Element-->
<div class="slider-list">
<div class="slider-item">
<div class="slider-image-container"><img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/image1.jpg" /></div>
<div class="slider-content-container">
<h1>B LIne: The Place to Be</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p><p>A photo credit.</p></p>
<p></p>
</div>
</div><div class="slider-item">
<div class="slider-image-container"><img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/anotherimage.jpg" /></div>
<div class="slider-content-container">
<h1>July 4th: You missed it!</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p></p>
<p></p>
</div>
</div><div class="slider-item">
<div class="slider-image-container"><img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/anotherimage.jpg" /></div>
<div class="slider-content-container">
<h1>Festival coming Aug. 31st!</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p></p>
<p></p>
</div>
</div>
</div>
</div>
<img src="http://www.someurl.com/images/icons/icon-chevron-left-slider.svg">
<img src="http://www.someurl.com/images/icons/icon-chevron-right-slider.svg">
<p class="slider-pagination"></p>
</div>
JavaScript
$('.popper').each(function () {
//var $thisPopper = $(this);
var hasContent = 0;
$('.photo-credit p').each(function () {
if($(this).html().length > 0) {
hasContent++;
}
});
if(hasContent > 0){
//$thisPopper.hide();
$(this).hide();
}
});
You were on the right direction. However a couple mistakes in your javascript.
You tried to target all the div with "popper" class. However, the div with "popper" and "photo-credit" are on the same level. Why not targeting their parent div instead?
Try this code. It's been tested (Link to jsfiddle)
$('.slider-item').each(function () {
var thisSilerItem = $(this);
var hasContent = 0;
thisSilerItem.find('.photo-credit p').each(function () {
if($(this).html().length > 0) {
hasContent++;
}
});
if(hasContent <= 0){
thisSilerItem.find('.popper').hide();
}
});
Edit:
Bonus:
If your page has a large amount of sliders, this jquery solution will cause some UX issues ("jumpy" div on/after page load)
Try a CSS only solution.
When you render your DOM elements. Add a class to "popper" div if the content of "photo-credit" is empty.
<div class="popper hide">
// img
</div>
Then in your CSS, add
.popper.hide { display: none; }
It's hard to fully gather what you want to do, but if I understand correctly...
$('.popper').each(function () {
var photoCredit = $(this).find(".photo-credit p")
if ( $(photoCredit).is(':empty') ){
$(this).hide();
}
});
It's worth pointing out that CSS4 developers are working on a 'has' selector but as of July 2017 there is no support for any browser just yet.
It is expected to work in the following manner:
.popper:has(> p:empty) { display: none }
I hope this helps... :)
You can check this code.
$.each($('.popper'), function (index, popper) {
var isEmptry = true;
$.each($(popper).next('.photo-credit').children(), function (index, ptag) {
if ($.trim($(ptag).html()) != '')
isEmptry = false;
});
if (isEmptry)
$(popper).hide();
});
Working code
$.each($('.popper'), function (index, popper) {
var isEmptry = true;
$.each($(popper).next('.photo-credit').children(), function (index, ptag) {
if ($.trim($(ptag).html()) != '')
isEmptry = false;
});
if (isEmptry)
$(popper).hide();
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div class="slider-wrapper">
<!--Required Root Element-->
<div class="slider">
<!--Required List Element-->
<div class="slider-list">
<div class="slider-item">
<div class="slider-image-container">
<img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/image1.jpg" />
</div>
<div class="slider-content-container">
<h1>B LIne: The Place to Be</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p>
<p>A photo credit.</p>
</p>
<p></p>
</div>
</div>
<div class="slider-item">
<div class="slider-image-container">
<img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/anotherimage.jpg" />
</div>
<div class="slider-content-container">
<h1>July 4th: You missed it!</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p></p>
<p></p>
</div>
</div>
<div class="slider-item">
<div class="slider-image-container">
<img class="slider-image" src="http://www.someurl.com/Images/Homepage Images/Slider/anotherimage.jpg" />
</div>
<div class="slider-content-container">
<h1>Festival coming Aug. 31st!</h1>
<div class="learn-more">Learn More</div>
</div>
<div class="popper">
<img data-toggle="popover" class="photo-credit-icon" src="http://www.someurl.com/icon-photography.svg" alt="photo credit" />
</div>
<div class="photo-credit hide">
<p></p>
<p></p>
</div>
</div>
</div>
</div>
<a href="#" class="slider-control-prev">
<img src="http://www.someurl.com/images/icons/icon-chevron-left-slider.svg"></a>
<a href="#" class="slider-control-next">
<img src="http://www.someurl.com/images/icons/icon-chevron-right-slider.svg"></a>
<p class="slider-pagination"></p>
</div>

jQuery - Get <p> text by variable ID

Here is my code:
var itemCount = 0;
var addTo = "";
$(".add").click(function(){
alert($(this).attr('id'));
var itemClicked = $(this).attr('id');
var a = parseInt(itemClicked);
alert($(".price").find('#' + a).text());
itemCount = itemCount + 1;
});
and
<div class="col-sm-5 col-md-4 col-sm-2">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3 class="item-header" id="1">iPhone</h3>
<p>...</p>
<p class="hidden" id="1">1</p>
<p class="price" id="1">19.95</p>
<p><button class="btn btn-primary add" role="button" id="1">Add to cart</button> More</p>
</div>
</div>
</div>
What I want to do is write a function takes figures out which button triggered the function, and retrieves the according price to the button. In this case I pressed 1, and I want the price according to Item 1.
When I perform alert(a); then I retrieve the number of 1. So I suppose something is wrong with the following line, just cant figure out what...
alert($(".price").find('#' + a).text());
Maybe you should add a data-price attribute (or something to reference to your actual data). I don't think it's a good practice to be dependant on the value of some paragraph tags. Better is to have a separation of display data and internal data.
You can access the data-price like this:
$('.button').click(function(e) {
console.log(e.target.getAttribute('data-price'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Shop</h1>
<p>iPhone 7</p>
<p>price € 110</p>
<button data-price="110" class="button">Add</button>
You don't need id:
$("button.add").click(function(){
var $card = $(this).parents("div.caption");
alert("adding good id:"+$card.children("input.good-id").val() + " with price: " + $card.children("p.price").text());
/* note - don't send price to backend,
it can be easily corrected in browser before click,
send only id of the good, and get price from DB */
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5 col-md-4 col-sm-2">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3 class="item-header">iPhone</h3>
<p>...</p>
<input type="hidden" class="good-id" name="goodId" value="1">
<p class="price">19.95</p>
<p><button class="btn btn-primary add" role="button">Add to cart</button> More</p>
</div>
</div>
</div>
I updated your html markup to use data attributes. In that way it will be easier for you to select the needed prices of certain items:
<p class="hidden" data-item="1">1</p>
<p class="price" data-price="1">19.95</p>
Demo:
$('.add').on('click', function() {
var itemId = $(this).attr('id');
var itemPrice = $('.price[data-price="'+ itemId +'"]').text();
alert(itemPrice);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-5 col-md-4 col-sm-2">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3 class="item-header" id="1">iPhone</h3>
<p>...</p>
<p class="hidden" data-item="1">1</p>
<p class="price" data-price="1">19.95</p>
<p>
<button class="btn btn-primary add" role="button" id="1">Add to cart</button> More</p>
</div>
</div>
</div>

Categories