JS Events - for loop - javascript

I'm creating a website database which will have roughly 80-100 cards of individual products in each one. Inside the cards there is a + and - button which changes an input element.
I have the counter code working fine but I need the buttons to be changing the input box in the card that is being pressed.
Is there any way to focus the click event so that it changes the input element inside it's div?
Should I be approaching this differently...
This is the complete card HTML:
<div class="card 688AttackSub">
<img src="688%20attach%20sub.jpg" alt="688 Attack Sub">
<div class="info-container">
<p>688 Attack Sub</p>
<p>1995</p>
<div class="no-sold">
<p>Number Sold</p>
<div class="buttons">
<button class="btn btn-outline-secondary btn-minus"><i class="fa fa-minus"></i></button>
<input class="form-control counter" min="0" name="quantity" value="1" type="number">
<button class="btn btn-outline-secondary btn-plus"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="sold-price">
<p>Total Sold Price</p>
<div class="buttons">
<button class="btn btn-outline-secondary btn-neg"><i class="fa fa-minus"></i></button>
<input class="form-control quantity counter-price" min="0" name="quantity" value="1" type="number">
<button class="btn btn-outline-secondary btn-add"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="av-price">
<p>Average Price</p><input class="form-control quantity avPrice" min="0" name="quantity" value="1" type="number">
</div>
<div class="last-sold">
<p>Last Sold Date</p><input class="form-control quantity lastSoldDate" min="0" name="quantity" value="1" type="number">
<p>Last Sold Price</p><input class="form-control quantity lastSoldPrice" min="0" name="quantity" value="1" type="number">
</div>
</div>
</div>
var buttonRed = document.querySelectorAll(".btn-minus");
var buttonPos = document.querySelectorAll(".btn-plus");
var buttonNeg = document.querySelectorAll(".btn-neg");
var buttonAdd = document.querySelectorAll(".btn-add");
var counter = document.querySelectorAll(".counter");
var counterPrice = document.querySelectorAll(".counter-price");
var averagePrice = document.querySelectorAll(".avPrice");
var lastSoldDate = document.querySelectorAll(".lastSoldDate");
var lastSoldPrice = document.querySelectorAll(".lastSoldPrice");
for (var i = 0; i < buttonRed.length; i++){
buttonRed[i].addEventListener("click", function() {
for (var m = 0; m < counter.length; m++){
counter[m].value = parseInt(counter[m].value) - 1;
} false;
} );}
for (var j = 0; j < buttonPos.length; j++){
buttonPos[j].addEventListener("click", function() {
for (var m = 0; m < counter.length; m++){
counter[m].value = parseInt(counter[m].value) + 1;
} false;
} );}
for (var k = 0; k < buttonNeg.length; k++){
buttonNeg[k].addEventListener("click", function() {
for (var n = 0; n < counterPrice.length; n++){
counterPrice[n].value = parseInt(counterPrice[n].value) - 1;
} false;
} );}
for (var l = 0; l < buttonAdd.length; l++){
buttonAdd[l].addEventListener("click", function() {
for (var n = 0; n < counterPrice.length; n++){
counterPrice[n].value = parseInt(counterPrice[n].value) + 1;
} false;
} );}

I ended up using Jquery as it has the $(this) input which will help with the 100 or so cards with identical class names
$(document).ready(function() {
$(".btn-minus").on('click', function(){
$(this).siblings($('.counter')).get(0).value--
});
});
$(document).ready(function() {
$(".btn-plus").on('click', function(){
$(this).prev($('.counter')).get(0).value++
});
});
$(document).ready(function() {
$(".btn-neg").on('click', function(){
$(this).siblings($('.counter-price')).get(0).value--
});
});
$(document).ready(function() {
$(".btn-add").on('click', function(){
$(this).prev($('.counter-price')).get(0).value++
});
});

Related

how to fix: Cannot read property 'value' of undefined

I am trying to get the value of the quantityElement so i can make the price change decrease/increase when the quantity goes down/up but i order for this to work i need to get the value of the quantityElement which keeps coming back as undefined in the console.
var removeCartitemButtons = document.getElementsByClassName('remove-btn')
console.log(removeCartitemButtons)
for (var i = 0; i < removeCartitemButtons.length; i++) {
var button = removeCartitemButtons[i]
button.addEventListener('click', function(event) {
console.log('clicked')
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
})
}
// Update Cart total price
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-info')
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('product-price')[0]
var quantityElement = cartRow.getElementsByClassName('quantity-value')
[0]
var price = parseFloat(priceElement.innerText.replace('R', ''))
var quantity = quantityElement.value
console.log(price * quantity)
}
}
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="250px">
<span class="product-price">R7400</span>
</div>
<span class="cart-item-title">Balenciaga Speed High</span>
</div>
<br>
<button class="remove-btn" type="button">Remove</button>
</div>
</div>
</div>
</td>
<td><input class="quantity-value" type="number" value="1"></td>
</tr>
You are trying to get 'quantity-value' field inside cartRow, but it does not exist inside the 'cart-info' div, because of which you are getting this value as undefined.
var quantityElement = cartRow.getElementsByClassName('quantity-value')[0]
Your html should probably be like below:
var removeCartitemButtons = document.getElementsByClassName('remove-btn')
console.log(removeCartitemButtons)
for (var i = 0; i < removeCartitemButtons.length; i++) {
var button = removeCartitemButtons[i]
button.addEventListener('click', function(event) {
console.log('clicked')
var buttonClicked = event.target
buttonClicked.parentElement.remove()
// updateCartTotal()
})
}
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7401</span>
<input class="quantity-value" type="number" value="1">
</div>
<span class="cart-item-title">Balenciaga Speed High1</span>
<button class="remove-btn" type="button">Remove1</button>
</div>
</td>
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7402</span>
<input class="quantity-value" type="number" value="2">
</div>
<span class="cart-item-title">Balenciaga Speed High2</span>
<button class="remove-btn" type="button">Remove2</button>
</div>
</td>
<td>
<div class="cart-items">
<div class="cart-info">
<img src="images/men3(balenciaga).png" width="450px">
<span class="product-price">R7403</span>
<input class="quantity-value" type="number" value="3">
</div>
<span class="cart-item-title">Balenciaga Speed High3</span>
<button class="remove-btn" type="button">Remove3</button>
</div>
</td>

Input's onclick event is not responding when i declare the name="band[ ]"

I want to limit the selection of checkboxes through limit_checkbox() function but when i declare the name of input to an array it is not responding. The error shows " Uncaught ReferenceError: limit_checkbox is not defined at HTMLInputElement.onclick"
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>
<script>
var a, b = false;
function limit_checkbox(max, obj) {
var x = document.getElementsByName("band");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
count += 1;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
</script>
Add[] in band i.e : document.getElementsByName("band[]") because javascript is not able to find that inputs .
Working Code :
var a, b = false;
function limit_checkbox(max, obj) {
//getting element by name
var x = document.getElementsByName("band[]");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
//incrementing
count++;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>

set default checked value at total cost display without using "value"

As we can directly set the value to the value we wanted in the textbox like <input type="text" name="total" value="500" size="10" readonly />
Is there any method to display the default checked value in the text box wihout using value = "500"??
var checks = document.getElementsByName('deliveryType');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
var cal = document.getElementsByName('deliveryType');
var total = 0;
for (var i = 0; i < cal.length; i++) {
if (cal[i].checked) {
total += parseFloat(cal[i].getAttribute("data-price"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
<form id= selectEvent>
<section id="collection">
<p>
Home - £500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked /> |
self collect - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly />
</section>
</form>
Try the following code:
var checks = document.getElementsByName('deliveryType');
checks.forEach(function(value){
if(value.checked){
document.getElementsByName("total")[0].value = "$" + value.getAttribute('data-price');
}
})
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
var cal = document.getElementsByName('deliveryType');
var total = 0;
for (var i = 0; i < cal.length; i++) {
if (cal[i].checked) {
total += parseFloat(cal[i].getAttribute("data-price"));
}
}
document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
<form id= selectEvent>
<section id="collection">
<p>
Home - £500.00 <input type="radio" name="deliveryType" value="home" data-price="500.00" checked /> |
self collect - no charge <input type="radio" name="deliveryType" value="ticketOffice" data-price="0" />
</p>
</section>
<section id="checkCost">
<h2>Total cost</h2>
Total <input type="text" name="total" size="10" readonly />
</section>
</form>

Javascript: Labeling array results

Alright so here is my Html code:
<html>
<head>
<title>Planning</title>
<script type="text/javascript" src="Function.js"></script>
</head>
<body>
<form id="form">
<h1><b>Please enter data</b></h1>
<hr size="3"/>
<br>
<label for="Name">Name:</label> <input id="Name" type="text" />
<br>
<label for="Date">Date: </label><input id="Date" type="text" />
<br>
<label for="Plans">Plans: </label><input id="Plans" type="text" />
<br>
<br>
<input type="button" value="Save" onclick="insert();">
<input type="button" value="Show data" onclick="show();"> <br>
<h2><b>Data:</b></h2>
<hr>
</form>
<div id="display">
</div>
</body>
</html>
And my Javscript:
var Name=new Array();
var Date=new Array();
var Plans=new Array();
function insert(){
var NameValue = document.getElementById('Name').value;
var DateValue = document.getElementById('Date').value;
var PlansValue = document.getElementById('Plans').value;
Name[Name.length]=NameValue;
Date[Date.length]=DateValue;
Plans[Plans.length]=PlansValue;
}
function show() {
var content="<b>Your Plans For the Day:</b><br>";
var Namelabel ="<p>Name</p>"
for(var i = 0; i < Name.length; i++) {
+ Namelabel;
content +=Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content +=Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content +=Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}
The code on its own works fine but what I for the life of me can't figure out how to do is add a label identifying what the data showed is.
example being "Name:" for the displayed names and "dates:" appearing before the displayed dates.
I have other parts of the document I need to do in the meantime but this is really bothering me.
Change you show function to this
function show() {
var content="<b>Your Plans For the Day:</b><br>";
for(var i = 0; i < Name.length; i++) {
content += "Name " + Name[i]+"<br>";
}
for(var i = 0; i < Date.length; i++) {
content += "Date" + Date[i]+"<br>";
}
for(var i = 0; i < Plans.length; i++) {
content += "Plans" + Plans[i]+"<br>";
}
document.getElementById('display').innerHTML = content;
}

Sum dynamic values from input text and radio

I'm trying to sum the value of an input text changing dynamically with a radio that also changes dynamically. I'm doing something right but also something wrong because it doesn't sum when I want. The sum should show everytime the input text changes and not randomly disappear then you click a radio, just sum them.
the fiddle http://jsfiddle.net/7tFhx/
and the code
<form id="myForm" accept-charset="UTF-8">
<button type="button" class="btn-tt btn-primary btn-lg" disabled>1. Elige el color</button></br>
<label>
<input class="calc" id="fb1" type="radio" name="fb" value="10">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb2" type="radio" name="fb" value="15">
<img src="img/02.jpg"/>
</label>
</br>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>2. Elige las medidas</button></br>
<div class="row">
<div class="col-xs-2">
ancho (cm.)
<input id="ancho" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
alto (cm.)
<input id="alto" type="text" class="form-control" placeholder="100">
</div>
<div class="col-xs-2">
cantidad
<input id="cantidad" type="text" class="form-control" placeholder="1">
</div>
</div>
</br>
<button type="button" class="btn-tt btn-primary btn-lg" disabled>3. Posición mecanismo</button></br>
<label>
<input class="calc" id="fb3" type="radio" name="fb1" value="20">
<img src="img/01.jpg"/>
</label>
<label>
<input class="calc" id="fb4" type="radio" name="fb1" value="35">
<img src="img/02.jpg"/>
</label>
<div>
Total: <span id="price">0</span>€
</div>
</form>
js:
$(function(){
var mecanismoMedida = ['100','200'];
var mecanismoPrecio = ['50','80'];
$('#ancho').on('input',function(){
var j = 1, i = 0;
value = parseInt(($("#ancho").val() / 8) + 1);
for(i = 0; i < mecanismoMedida.length; i++){
if($("#ancho").val() >= mecanismoMedida[i] && $("#ancho").val() <
mecanismoMedida[j]){
value += mecanismoPrecio[i];
break;
} else {
j++;
}
}
$("#price").text(this.value + value);
});
$('#myForm input[type="radio"]').on('change', function () {
var sum = 0;
$("#myForm").find("input[type='radio']:checked").each(function () {
sum += parseInt(this.value);
});
$("#price").text(sum);
});
});
If it's a simple sum you're after, you can simply run an update code on the keyup and change events of all input elements:
$("input").change(function(){update();}).keyup(function(){update();});
To update them, first you need to check and see which one of the two radio buttons are checked and get its value:
function update(){
var p = 0;
for(var i = 0; i < $(".calc").val(); i++)
{
if($($(".calc")[i]).prop("checked") == true)
{
p += parseInt($($(".calc")[i]).val());
}
}
After that, simply parse the values of the textboxes to integers and add them to the value of the radio button. I created a custom function to do this, because if the boxes are empty, parsing them returns NaN:
p = parseInt(p);
p += parseInt(val2($("#ancho")));
p += parseInt(val2($("#alto")));
p += parseInt(val2($("#cantidad")));
p = parseInt(p);
$("#price").html(p);
}
function val2(elm){
if(isNaN(parseInt($(elm).val())))
return 0;
else
return parseInt($(elm).val());
}
JSFiddle

Categories