In the code I wrote, overlayBtn.addEventListener
triggers nested event amtBtn.addEventListener
to grab quantiy.value
from a local scope and insert it into a global variable getquantity
. Then a <p>
element will be created to hold getquantity
and attached to listContainer
.
However, when I console log getquantity
in overlayBtn.addEventListener
it logs as undefined, thereby the code cannot proceed to add the value in the created <p>
element. I don’t know why this is happening. Is there a way to make getquantity
get the intended value and not come up as undefined? I would really appreciate if you guys could help me out in this one.
Here’s the code:
JS
const overlay = document.querySelector('.overlay');
const overlayBtn = document.querySelector('.overlay-btn');
var quantity = document.querySelector('.quantity');
var amtBtn = document.querySelector('.amt-btn');
const formAmount = document.querySelector('.form-amount');
const sucMsg = document.querySelector('.suc-msg');
const listContainer = document.querySelector('list-container');
let getQuantity;
overlayBtn.addEventListener('click', function(){
overlay.style.display = "block";
amtBtn.addEventListener('click', function(e){
e.preventDefault();
getQuantity = quantity.value; //Value gotten from local scope
formAmount.classList.add('hide-form-amount');
sucMsg.classList.add('show-suc-msg');
setTimeout(returnNormal, 1000);
function returnNormal(){
overlay.style.display = "none";
sucMsg.classList.remove('show-suc-msg');
formAmount.classList.remove('hide-form-amount');
}
});
console.log(getQuantity); //Will come up as undefined
const para = document.createElement('p');
para.innerHTML = `${getQuantity}`;
listContainer.prepend(para);
});
CSS
.overlay-btn{
padding: 50px;
}
.overlay{
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 2;
cursor: pointer;
display: none;
}
.showOverlay{
display: block;
}
.form-amount{
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #2C8F77;
visibility: visible;
}
.hide-form-amount{
visibility: hidden;
}
.suc-msg{
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #2C8F77;
color: white;
visibility: hidden;
}
.show-suc-msg{
visibility: visible;
}
.list-container{
height: 500px;
width: 300px;
background-color: #2C8F77;
color: aliceblue;
overflow: scroll;
}
HTML
<button class="overlay-btn">add to list</button>
<div class="overlay">
<div class="amountPopUp">
<form class="form-amount">
<label for="quantity">Quantity:</label>
<input type="number" class="quantity" name="quantity" min="1" max="100">
<input type="submit" class="amt-btn" value="Enter" name="quantity">
</form>
<div class="suc-msg">
<h4>Item(s) added successfully</h4>
</div>
</div>
</div>
<div class="list-container"></div>