Undefine Input Value on function - javascript

I'm completely new on this, but I'm trying to make a shopping cart with javaScript.
Everything were fine till I tried to add an input value to the items added to the cart.
I have an image, a price and a name, but I need to add a "QTY" field.
this is the input of that field:
<input type="number" id="store-item-qty" type="qty" placeholder="QTY" name="text_name" class="store-item-qty">
and this is my script
//value of qty---->
let qty =
event.target.parentElement.parentElement.nextElementSibling.children[0].children[2].value;
//add items to cart--->
cartItem.innerHTML = `
<img src="${item.img}" class="img-fluid" id="item-img" alt="">
<div class="item-text">
<p id="cart-item-title" class="font-weight-bold mb-0">${item.name}</p>
<p> </p>
<span id="cart-item-girth" class="cart-item-girth" class="mb-0">${item.girth}</span>
</div>
<p class="store-item-qty" type="qty" id="store-item-qty">${item.qty}</p>
<a href="#" id='cart-item-remove' class="cart-item-remove">
<i class="fas fa-trash"></i>
</a>
</div>
`;
//var qty--->
var qty = "qty";
document.getElementById("store-item-qty").value;
But when I click "add to cart" it works importing the info of everything except the QTY field and says just "Undefine"

First you get the value of Element quantitiy and define it like let qty = ....
And in your template you try to read qty from ${item.qty}.
Should read ${qty} AFAIK.

Related

How can i add variable to input value using jQuery?

I have a variable and i want to add it to an input value
The variable is names text
Put the text variable to the input value
<div class="swiper-slide">
<i class="button fa-regular fa-pen-to-square" id="update_pen" ></i>
<div class="services-item mb-40 elementor-repeater-item-78d8e80" id="swiper-slide-one">
<div class="services-item__content">
<h4 class="services-item__tp-title mb-30" id="h_foor">
BIOCHIMIE
</h4>
<div class="text_area_box" id="text_area_box">
<input type="text" name="" required="" value=""> <--- add the variable to this value
<label>Titre</label>
</div>
</div>
</div>
</div>
Here is the javascript code :
document.querySelectorAll('i.button').forEach(el => {
el.addEventListener('click', e => {
var element = document.querySelector(".text_area_box");
var elementactive = document.querySelector(".text_area_box_active");
if(element.classList.contains('text_area_box')) /*the condition works perfectly*/
{
element.classList.remove('text_area_box');
element.classList.add('text_area_box_active');
}
if(elementactive.classList.contains('text_area_box_active')){
elementactive.classList.remove('text_area_box_active');
elementactive.classList.add('text_area_box');
}
const parent = e.target.closest('.swiper-slide');
const text = parent.querySelector('a').textContent; //this variable
});
});
i would highely appriciate any help.
Salut !
After your
const text = parent.querySelector('a').textContent; //this variable
maybe you can try to select your closest input type text and do a myInputelement.val(text) ?

JQuery won't set right value onclick of button

So what I'm trying to achieve is to set the value of a hidden input so that I can send that value to a PHP file where this value will be used to execute a delete query.
The only problem that I'm facing is that it will only select the data-id from the first element, which is not what I want.
Here is the JQuery code, if any other files are required for more info I'll post those aswell.
$('document').ready(function(){
// Makes menu visibility toggable
$('#hamburger_btn').on("click", function() {
$('#sidemenu').toggleClass("show");
})
// Closes menu via separate button
$('#close_btn').on("click", function() {
$('#sidemenu').removeClass("show");
})
// Opens dialogbox
$('.openDialog').on("click", function() {
$('#dialog').addClass("showBox");
$('#overlay').addClass("showOv");
// Sets the input value in dialog
$('#post_id').val($('.openDialog').data("id")); // Here lies the problem
})
// Closes dialogbox
$('#closeDialog').on("click", function() {
$('#dialog').removeClass("showBox");
$('#overlay').removeClass("showOv");
// Sets value to empty and remove attribute value
$('#post_id').val('').removeAttr("value");
})
});
If this question has already been answered elsewhere please let me know aswell, because I couldnt find it.
EDIT:
The HTML
<?php
// Get all posts from DB
$sql = "SELECT * FROM cm_posts";
$stmt = $conn->prepare($sql);
$stmt->execute();
$results = $stmt->get_result();
?>
<section class="s-reset s-posts-overview">
<div id="top"></div>
<div class="posts-overview-content-wrapper">
<h3 class="s-title">Overview</h3>
<div class="post-cards-container">
<?php // Display all posts in a card ?>
<?php while($row = $results->fetch_assoc()):?>
<div class="post-card">
<h4 class="card-title"><?php echo $row["post_title"];?></h4>
<h5 class="card-sub-title"><?php echo $row["post_date"];?></h5>
<div class="card-btn">
<button>View</button>
<button class="btn-small openDialog" id="openDialog" data-id="<?php echo $row["post_id"];?>">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
<?php endwhile ?>
</div>
<div class="scroll-btn">
<a href="#top" class="button">
<i class="fas fa-arrow-up"></i>
</a>
<a href="#bottom" class="button">
<i class="fas fa-arrow-down"></i>
</a>
</div>
</div>
<div id="bottom"></div>
</section>
<div class="overlay" id="overlay"></div>
<div class="dialog" id="dialog">
<div class="dialog-content-wrapper">
<h3>Are you sure you want to delete this item?</h3>
<form action="data/post_db_files/delete-post-db.php" method="post" id="del_post_item">
<input type="hidden" id="post_id" name="post_id">
<input type="submit" value="Delete" id="del_post" class="del_post">
</form>
<button id="closeDialog" class="close-btn">Cancel</button>
</div>
</div>
Picture of the browser with devtools
The image shows where the id is supposed to appear, now if i click the delete button on any of these elements, I always get the value of 1, but if I select "hello 2" which has a post_id of 2 I want that id to appear in the hidden input. I hope this clears somethings up.
You are trying to get the data-id of the clicked item, but you are using $('.openDialog') => This would get all elements wich class is openDialog.
Use this instead:
$('#post_id').val($(this).data("id"));
you can also create on onClick function on this button like this & pass value in that function
<button id="openDialog onClick=openDialogButtonClick("<php echo $row["post_id"];>")>
after this just create function in your Js file or tag
function openDialogButtonClick(id){
//in this id param you will get id then set this id to your hidden field
$("#post_id").val(id);
}

Jquery click function not working for all the ids

I have created a page which contains all the products from the database, and this is dynamic page. Columns are created in loop. Whenever user clicks the product i am fetching the product id which is unique, however this is working only for one product, for next product even if click the function is not triggered. below is the code for reference.
{{ album.product_name }}
Category : {{ album.product_category }}
Price : {{ album.product_price }}
$(document).ready(function() {
$('#k').click(function(){
var a = $('#custId').val();
alert(a)
console.log(a)
});
This is working perfectly fine for the first product only i.e the first product from the loop. for rest the click function is not working. Please help!
Below is the HTML code:
<div class="card-body">
<a href="#" id="k">
<img src="qph.fs.quoracdn.net/…" class="card-img-top" alt="..." height="90px" width="85px" id="k">
</a>
<h5 class="card-title">{{ album.product_name }}</h5>
<p class="card-text">Category : {{ album.product_category }}</p>
<p class="card-text">Price : {{ album.product_price }}</p>
<input type="hidden" id="custId" value={{ album.id }}>
</div>
You cannot have multiple elements with the same ID. Consider adding a common class name to all the target elements, say myClass, then you can bind the desired event using:
$('.myClass').click(function(){
//your code here...
});
Explanation: The browser assumes you only have one element with an id of k (because is should be like so by convention), therefore $("#k") will only target the first element with that ID.

How to select the right Id when clicked?

I am displaying users in a list with their photo, name etc... and then I am grabbing the value of the element that has the id "uid" :
$scope.toUserView = function() {
var uid = document.getElementById('userUID').textContent;
console.log(uid);
$state.go('tab.userview');
};
Problem is that whoever I click on, I always get the reference of the FIRST user in the list of the page and I would like to grab only the one I click on.
I tried to add .click() at the end of my var but it is not a function.
Any idea ?
EDIT : Corresponding HTML :
<ion-list class="item-border-off list-fav">
<a ><ion-item ng-click="toUserView()" ng-repeat="user in users" class="item-remove-animate item-avatar">
<img ng-src="{{user.photoURL}}">
<h2>
{{user.name}}
</h2>
<p >{{user.description}}</p>
<p id="userUID">{{user.uid}}</p>
<!-- button options -->
<ion-option-button>
<i class="icon ion-ios-trash-outline"></i>
</ion-option-button>
<ion-option-button>
<i class="icon ion-ios-chatbubble-outline"></i>
</ion-option-button>
</ion-item></a>
</ion-list>
Corresponding HTML
<a ><ion-item ng-click="toUserView($index)" ng-repeat="user in users" class="item-remove-animate item-avatar">
<img ng-src="{{user.photoURL}}">
<h2 id={{user.uid}}>
{{user.name}}
</h2>
<p >{{user.description}}</p>
<p id="userUID{{$index}}">{{user.uid}}</p>
<!-- button options -->
<ion-option-button>
<i class="icon ion-ios-trash-outline"></i>
</ion-option-button>
<ion-option-button>
<i class="icon ion-ios-chatbubble-outline"></i>
</ion-option-button>
</ion-item></a>
JS
$scope.toUserView = function(ind) {
var uid = document.getElementById('userUID'+ind).textContent;
console.log(uid);
$state.go('tab.userview');
};
You seem to repeat the <p id="userUID"></p> in a loop.
id attributes should be unique to a page by definition.
document.getElementById('test') returns the first element having the id attribute set to test.
You should either add something unique to your ids, or use class="userUID" instead.

How to hide "div" from js, which use information from spring?

In my website, on UI I show information from DB, use "spring". I want to make, if items quantity equals 0, then I hide this "div". If items quantity more than 0, then I show "div"
In html I recive from spring:
<div th:each="viewAvailableWhisky : ${viewAvailableWhisky}">
<div class="tilt pic" id="ShowHide">
<a th:href="#{~/buySelectedWhisky(nameBuyWhiskey=${viewAvailableWhisky.id})}" >
<img th:attr="src=${viewAvailableWhisky.photo}" id="photoId" width="150" height="250"/>
<div>
<b> <span th:text="${viewAvailableWhisky.nameWhisky}">Name</span></b>
</div>
<div>
<b> Quantity: <span th:text="${viewAvailableWhisky.quantityWhisky}"
>quantityWhisky</span>piece</b>
<input type="hidden" id="quantity" th:value="${viewAvailableWhisky.quantityWhisky}"/>
</div>
<div>
<b> $ <span th:text="${viewAvailableWhisky.price}">Price</span></b>
</div>
</a>
</div>
</div>
I think, it's better to make the with use a JS. But I don't understand how, I try use this code. This code can't catch
quantity of goods of each item from a DB
$(document).ready ( function(){
var quantityItems = $("#quantity").val();
console.log(quantityItems);
if(quantityItems>0){
$("#ShowHide").show();
}
else {
$("#ShowHide").hide();
}
});
The th:if="${condition}" attribute is used to display a section of the view if the condition is met.
<span th:if="${student.gender} == 'M'" th:text="Male" />
Furthemore, thymeleaf offers option to display certain section if given condition is NOT met using th:unless
<span th:unless="${student.gender} == 'M'" th:text="Female" />
(For further info see This tutorial or this intro to Thymeleaf conditionals)
To display certain content only if user has specific role, use spring security's integration with thymeleaf.
<div sec:authorize="hasRole('ROLE_ADMIN')">
This content is only shown to administrators.
</div>
More info about Spring Security integration here.

Categories

Resources