I'm learning and practicing Javascript publish-subscribe design pattern.
Here is the code: https://codesandbox.io/s/javascript-forked-5vb602?file=/index.js.
What my issue is, when I want to calculate the most expensive unit, when the previous most expensive unit change to 0, I don't know how to find a new highest unit value.
On the most-expensive-minus, I can only find the corresponding unit price, but not others. So how can I find other values?
This is the whole code:
HTML:
<div id="root">
<div id="box">
<ul>
<li>
<input type="button" value="-" />
<span class="num">0</span>
<input type="button" value="+" />
<span>single price:</span>
$<span class="unit">15;</span>
<span class="label">total:</span>
$<span class="subtotal">0</span>
</li>
<li>
<input type="button" value="-" />
<span class="num">0</span>
<input type="button" value="+" />
<span>single price:</span>
$<span class="unit">10;</span>
<span class="label">total:</span>
$<span class="subtotal">0</span>
</li>
<li>
<input type="button" value="-" />
<span class="num">0</span>
<input type="button" value="+" />
<span>single price:</span>
$<span class="unit">5;</span>
<span class="label">total:</span>
$<span class="subtotal">0</span>
</li>
<li>
<input type="button" value="-" />
<span class="num">0</span>
<input type="button" value="+" />
<span>single price:</span>
$<span class="unit">2;</span>
<span class="label">total:</span>
$<span class="subtotal">0</span>
</li>
<li>
<input type="button" value="-" />
<span class="num">0</span>
<input type="button" value="+" />
<span>single price:</span>
$<span class="unit">1;</span>
<span class="label">total:</span>
$<span class="subtotal">0</span>
</li>
</ul>
<div class="total-box">
total purchase
<span id="goods-num">0</span>
; total cost $
<span id="total-price">0</span>
; most expensieve single one is $<span id="unit-price">0</span>
</div>
</div>
</div>
Javascript:
const Event = {
userList: {},
subscribe(key, fn) {
if (!this.userList[key]) {
this.userList[key] = [];
}
this.userList[key].push(fn);
},
publish() {
const key = Array.prototype.shift.apply(arguments);
const fns = this.userList[key];
if (!fns || fns.length === 0) {
return false;
}
for (let i = 0, len = fns.length; i < len; i++) {
fns[i].apply(this, arguments);
}
}
};
(function () {
const aBtnMinus = document.querySelectorAll("#box li>input:first-child");
const aBtnPlus = document.querySelectorAll("#box li>input:nth-of-type(2)");
const oTotalPrice = document.querySelector("#total-price");
const oUnitPrice = document.querySelector("#unit-price");
let curUnitPrice = 0;
for (let i = 0, len = aBtnMinus.length; i < len; i++) {
aBtnMinus[i].index = aBtnPlus[i].index = i;
aBtnMinus[i].onclick = function () {
this.parentNode.children[1].innerHTML > 0 &&
Event.publish("total-goods-num-minus");
--this.parentNode.children[1].innerHTML < 0 &&
(this.parentNode.children[1].innerHTML = 0);
curUnitPrice = this.parentNode.children[4].innerHTML;
Event.publish(
`minus-num${this.index}`,
parseInt(curUnitPrice),
parseInt(this.parentNode.children[1].innerHTML)
);
Event.publish(
`total-minus`,
parseInt(curUnitPrice),
parseInt(this.parentNode.children[1].innerHTML),
parseInt(oTotalPrice.innerHTML)
);
Event.publish(
`most-expensive-minus`,
parseInt(curUnitPrice),
parseInt(this.parentNode.children[1].innerHTML),
parseInt(oUnitPrice.innerHTML)
);
};
aBtnPlus[i].onclick = function () {
this.parentNode.children[1].innerHTML >= 0 &&
Event.publish("total-goods-num-plus");
this.parentNode.children[1].innerHTML++;
curUnitPrice = this.parentNode.children[4].innerHTML;
Event.publish(
`plus-num${this.index}`,
parseInt(curUnitPrice),
parseInt(this.parentNode.children[1].innerHTML)
);
Event.publish(
`total-plus`,
parseInt(curUnitPrice),
parseInt(this.parentNode.children[1].innerHTML),
parseInt(oTotalPrice.innerHTML)
);
Event.publish(
`most-expensive-plus`,
parseInt(curUnitPrice),
parseInt(oUnitPrice.innerHTML)
);
};
}
})();
(function () {
const aSubtotal = document.querySelectorAll("#box .subtotal");
const oGoodsNum = document.querySelector("#goods-num");
const oTotalPrice = document.querySelector("#total-price");
const oUnitPrice = document.querySelector("#unit-price");
Event.subscribe("total-goods-num-plus", function () {
++oGoodsNum.innerHTML;
});
Event.subscribe("total-goods-num-minus", function () {
--oGoodsNum.innerHTML;
});
Event.subscribe(`total-plus`, function (unitPrice, num, originalPrice) {
oTotalPrice.innerHTML =
originalPrice - unitPrice * (num - 1) + unitPrice * num;
});
Event.subscribe(`total-minus`, function (unitPrice, num, originalPrice) {
if (num > 0)
oTotalPrice.innerHTML =
originalPrice + unitPrice * (num - 1) - unitPrice * num;
});
Event.subscribe(`most-expensive-plus`, function (
unitPrice,
originalMostExpensive
) {
oUnitPrice.innerHTML =
originalMostExpensive < unitPrice ? unitPrice : originalMostExpensive;
});
Event.subscribe(`most-expensive-minus`, function (
unitPrice,
num,
originalMostExpensive
) {
if (num > 0) {
oUnitPrice.innerHTML =
originalMostExpensive < unitPrice ? unitPrice : originalMostExpensive;
} else {
oUnitPrice.innerHTML = "xx"; //how to find the new highest price?;
}
});
for (let i = 0, len = aSubtotal.length; i < len; i++) {
Event.subscribe(`minus-num${i}`, function (unitPrice, num) {
aSubtotal[i].innerHTML = unitPrice * num;
});
Event.subscribe(`plus-num${i}`, function (unitPrice, num) {
aSubtotal[i].innerHTML = unitPrice * num;
});
}
})();
Related
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++
});
});
I am trying to make an HTML website that sells pens, pencils and erasers. My issue is integrating the JavaScript into my HTML page. Everything has been working properly up until the last couple chunks of JavaScript any thoughts on how I could fix this problem.
<!DOCTYPE html>
<html>
<head>
<title>Pens, Pencils and Erasers</title>
<meta name="description" content="This is the description">
<link rel="stylesheet" href="style.css" />
<script src="store.js" async></script>
</head>
<body>
<header class="main-header">
<nav class="main-nav nav">
<ul>
<li>HOME</li>
</ul>
</nav>
<h1 class="store-name store-name-large">Pens, Pencils and Erasers</h1>
</header>
<section class="container content-section">
<div class="shop-items">
<span class="shop-item-title">Pen</span>
<img class="shop-item-image" src="pen.jpg">
<div class="shop-item-details">
<span class="shop-item-price">$0.50</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Pencil</span>
<img class="shop-item-image" src="pencil.webp">
<div class="shop-item-details">
<span class="shop-item-price">$0.30</span>
<button class="btn btn-primary shop-item-button"type="button">ADD TO CART</button>
</div>
</div>
<div class="shop-item">
<span class="shop-item-title">Eraser</span>
<img class="shop-item-image" src="eraser.png">
<div class="shop-item-details">
<span class="shop-item-price">$1.00</span>
<button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
</div>
</div>
</section>
<section class="container content-section">
<h2 class="section-header">CART</h2>
<select id = "province">
<option value= "saskatchewan" data-shipping-cost= "0" data-tax= "0.05" data-deal-limiter= "30" data-deal-coupon= "5">Saskatchewan</option>
<option value= "alberta" data-shipping-cost= "2" data-tax= "0.05" data-deal-limiter= "0" data-deal-coupon= "0">Alberta</option>
<option value= "manitoba" data-shipping-cost= "2" data-tax= "0.06" data-deal-limiter= "0" data-deal-coupon= "0">Manitoba</option>
</select>
<div class="cart-row">
<span class="cart-item cart-header cart-column">ITEM</span>
<span class="cart-price cart-header cart-column">PRICE</span>
<span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
<strong class="cart-total-title">Total</strong>
<span class="cart-total-price">$0</span><br><br>
</div>
<button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>
</section>
<script>
if (document.readyState == 'loading') {
document.addEventListener('DOMContentLoaded', ready)
} else {
ready()
}
function ready() {
var removeCartItemButtons = document.getElementsByClassName('btn-danger')
for (var i = 0; i < removeCartItemButtons.length; i++) {
var button = removeCartItemButtons[i]
button.addEventListener('click', removeCartItem)
}
var quantityInputs = document.getElementsByClassName('cart-quantity-input')
for (var i = 0; i < quantityInputs.length; i++) {
var input = quantityInputs[i]
input.addEventListener('change', quantityChanged)
}
var addToCartButtons = document.getElementsByClassName('shop-item-button')
for (var i = 0; i < addToCartButtons.length; i++) {
var button = addToCartButtons[i]
button.addEventListener('click', addToCartClicked)
}
document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}
function purchaseClicked() {
alert('Thank you for your purchase')
var cartItems = document.getElementsByClassName('cart-items')[0]
while (cartItems.hasChildNodes()) {
cartItems.removeChild(cartItems.firstChild)
}
updateCartTotal()
}
function removeCartItem(event) {
var buttonClicked = event.target
buttonClicked.parentElement.parentElement.remove()
updateCartTotal()
}
function quantityChanged(event) {
var input = event.target
if (isNaN(input.value) || input.value <= 0) {
input.value = 1
}
updateCartTotal()
}
function addToCartClicked(event) {
var button = event.target
var shopItem = button.parentElement.parentElement
var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
addItemToCart(title, price, imageSrc)
updateCartTotal()
}
function addItemToCart(title, price, imageSrc) {
var cartRow = document.createElement('div')
cartRow.classList.add('cart-row')
var cartItems = document.getElementsByClassName('cart-items')[0]
var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
for (var i = 0; i < cartItemNames.length; i++) {
if (cartItemNames[i].innerText == title) {
alert('This item is already added to the cart')
return
}
}
var cartRowContents = `
<div class="cart-item cart-column">
<img class="cart-item-image" src="${imageSrc}" width="100" height="100">
<span class="cart-item-title">${title}</span>
</div>
<span class="cart-price cart-column">${price}</span>
<div class="cart-quantity cart-column">
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">REMOVE</button>
</div>`
cartRow.innerHTML = cartRowContents
cartItems.append(cartRow)
cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}
function updateCartTotal() {
var cartItemContainer = document.getElementsByClassName('cart-items')[0]
var cartRows = cartItemContainer.getElementsByClassName('cart-row')
var order_total = 0
for (var i = 0; i < cartRows.length; i++) {
var cartRow = cartRows[i]
var priceElement = cartRow.getElementsByClassName('cart-price')[0]
var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
var price = parseFloat(priceElement.innerText.replace('$', ''))
var quantity = quantityElement.value
order_total = order_total + (price * quantity)
}
order_total = Math.round(order_total * 100) / 100
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + order_total
}
document.getElementById("province").addEventListener("change", function() {
const select = document.getElementById("province")
selectedProvince = select.options[select.selectedIndex]
shippingCost = selectedProvince.dataset.shippingCost
tax = selectedProvince.dataset.tax
dealLimiter = selectedProvince.dataset.dealLimiter,
dealCoupon = selectedProvince.dataset.dealCoupon;
});
if (selectedProvince.value === saskatchewan) {
shippingCost = "0"
tax = order_total * 0.05
dealLimiter = "30"
dealCoupon = "5"
document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon
}
if (selectedProvince.value === alberta) {
shippingCost = "2"
tax = order_total * 0.05
dealLimiter = "0"
dealCoupon = "0"
document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon
} if (selectedProvince.value === manitoba) {
shippingCost = "2"
tax = order_total * 0.06
dealLimiter = "0"
dealCoupon = "0"
document.getElementById("cart-subtotal-price").value = order_total + shippingCost + tax - dealCoupon
}
</script>
</body>
</html
I expect if Saskatchewan is chosen it should include a 5% tax onto the sales price and if they spend $30 they get $5 taken off. If Alberta is selected they would get $2 shipping added and 5% tax added onto the sales price. If Manitoba is selected they would get $2 shipping added and 6% tax added onto the sales price.
I've gone and spent the time to clean up your code and the errors within in. Please compare my snippet below with your code to understand the issues.
You will be able to copy paste it in replacing the old code and it will work as I worked off of what you had initially.
function updateCartTotal() {
const cartItemContainer = document.getElementsByClassName('cart-items')[0],
cartRows = cartItemContainer.getElementsByClassName('cart-row');
let sub_total = 0;
for (let i = 0; i < cartRows.length; i++) {
const cartRow = cartRows[i],
priceElement = cartRow.getElementsByClassName('cart-price')[0],
quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0],
price = parseFloat(priceElement.innerText.replace('$', '')),
quantity = quantityElement.value;
sub_total += (price * quantity);
}
const order_total = Math.round(calculateTotal(sub_total) * 100) / 100;
document.getElementsByClassName('cart-total-price')[0].innerText = '$' + order_total;
}
function calculateTotal(sub_total){
const select = document.getElementById("province"),
selectedProvince = select.options[select.selectedIndex],
shippingCost = selectedProvince.dataset.shippingCost,
tax = selectedProvince.dataset.tax,
dealLimiter = selectedProvince.dataset.dealLimiter,
dealCoupon = selectedProvince.dataset.dealCoupon,
appliedCoupon = parseFloat(sub_total) > parseFloat(dealLimiter) ? parseFloat(dealCoupon) : 0,
pretotal = ((sub_total + parseFloat(shippingCost) - appliedCoupon)),
total = pretotal + (pretotal * parseFloat(tax));
return total;
}
document.getElementById("province").addEventListener("change", calculateTotal());
function add() {
var txtNumber = document.getElementById("book");
var newNumber = parseInt(book.value) + 1;
book.value = newNumber;
}
function sub() {
var txtNumber = document.getElementById("book");
var newNumber = parseInt(book.value) - 1;
book.value = newNumber;
}
<div class="range">
<label>Book</label>
subtract<input type="text" id="book" value="0" min="0"> Add
</div>
<div class="range">
<label>Pen</label>
subtract<input type="text" id="pen" value="0" min="0"> Add
</div>
How to use same function for different Id's?
I tried using "this" keyword for selecting a current Id but it didn't work...
and i am trying do this in javascript only instead of jquery.
You could use the id as parameter for calling the functions. Inside take the value and convert it to number and if falsey, like NaN take a zero as value.
function add(id) {
var element = document.getElementById(id),
value = +element.value || 0;
element.value = value + 1;
}
function sub(id) {
var element = document.getElementById(id),
value = +element.value || 0;
value--;
if (value < 0) {
value = 0;
}
element.value = value;
}
<div class="range">
<label>Book</label>
<i class="fa fa-minus-circle" aria-hidden="true">-</i><input type="text" id="book" value="0" min="0">
<i class="fa fa-plus-circle" aria-hidden="true">+</i>
</div>
<div class="range">
<label>Pen</label>
<i class="fa fa-minus-circle" aria-hidden="true">-</i><input type="text" id="pen" value="0" min="0">
<i class="fa fa-plus-circle" aria-hidden="true">+</i>
</div>
Input free version with an object as storage.
function add(id) {
storage[id] = storage[id] || 0;
document.getElementById(id).innerHTML = ++storage[id];
}
function sub(id) {
storage[id] = storage[id] || 0;
--storage[id];
if (storage[id] < 0) {
storage[id] = 0;
}
document.getElementById(id).innerHTML = storage[id];
}
var storage = {};
<label>Book</label> - <span id="book">0</span> +<br>
<label>Pen</label> - <span id="pen">0</span> +</i>
pass id name in function like add('book') or add('pen') and this use in function call in javascript
and also use txtNumber instead of book in java script
function add(id) {
var txtNumber = document.getElementById(id);
var newNumber = parseInt(txtNumber.value) + 1;
txtNumber.value = newNumber;
}
function sub(id) {
var txtNumber = document.getElementById(id);
var newNumber = parseInt(txtNumber.value) - 1;
txtNumber.value = newNumber;
}
<div class="range">
<label>Book</label>
subtract<input type="text" id="book" value="0" min="0"> Add
</div>
<div class="range">
<label>Pen</label>
subtract<input type="text" id="pen" value="0" min="0"> Add
</div>
i'm trying to do an price counter synchronizing with increment and decrement buttons, but the price is not changing when i click one of the buttons (+/-) this is not working, how can i solve this issue? Thanks!!!
$('#plus').click(function add() {
var $qtde = $("#quantity");
var a = $qtde.val();
a++;
$("#minus").attr("disabled", !a);
$qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());
$('#minus').click(function minust() {
var $qtde = $("#quantity");
var b = $qtde.val();
if (b >= 1) {
b--;
$qtde.val(b);
}
else {
$("#minus").attr("disabled", true);
}
});
/* On change */
$(document).ready(function()
{
function updatePrice()
{
var price = parseFloat($("#quantity").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total-price").val(total);
}
$(document).on("change, keyup, focus", "#quantity", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value=""/>
If you change your binding to update whenever there is a click on an input, you'll get the behavior that you are expecting.
$('#plus').click(function add() {
var $qtde = $("#quantity");
var a = $qtde.val();
a++;
$("#minus").attr("disabled", !a);
$qtde.val(a);
});
$("#minus").attr("disabled", !$("#quantity").val());
$('#minus').click(function minust() {
var $qtde = $("#quantity");
var b = $qtde.val();
if (b >= 1) {
b--;
$qtde.val(b);
} else {
$("#minus").attr("disabled", true);
}
});
/* On change */
$(document).ready(function() {
function updatePrice() {
var price = parseFloat($("#quantity").val());
var total = (price + 1) * 1.05;
var total = total.toFixed(2);
$("#total-price").val(total);
}
// On the click of an input, update the price
$(document).on("click", "input", updatePrice);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="minus" />
<input type="text" id="quantity" value="" name="quantity" />
<input type="button" value="+" id="plus" />
<br />
<input id="total-price" readonly="readonly" value="" />
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="sp-quantity">
<div class="container" style=" font-size:14px; ">
<div class="sp-input">
<input type="text" class="quantity-input" value="1">
<div class="button" style="cursor: pointer;">
+
</div>
<div class="button" style="cursor: pointer;">
-
</div>
</div>
<p>custom filed</p>
<div class="sp-input">
<input type="text" class="quantity-input-db" value="1.8" step="1.8">
<div class="button" style="cursor: pointer;">
+
</div>
<div class="button" style="cursor: pointer;">
-
</div>
</div>
</div>
</div>
<script type="text/javascript">
// debugger;
$(document).ready(function () {
$(".button").on("click", function() {
var $db_value = $('.db_value').val();
var $quantity = $('.quantity_input').val();
var db_valu_fix = 1.8;
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quantity-input");
var oldValue_q = $input.val();
var $db_value = $button.closest('.sp-quantity').find("input.quantity-input-db");
var oldValue_db = $db_value.val();
console.log(oldValue_db);
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue_q) + 1;
newdbVal = parseFloat(oldValue_db) + 1;
//newdbVal.toFixed(2);
}
else {
if (oldValue_q > 0) {
newVal = parseFloat(oldValue_q) - 1;
newdbVal = parseFloat(oldValue_db) - 1;
newdbVal = Math.round(newdbVal * 100) / 100;
} else {
newVal = 1;
}
}
$input.val(newVal);
$db_value.val(newdbVal);
});
// $(".ddd").on("click", function(step) {
// var a=$(".quantity-input").val();
// var attr=$(".quantity-input").attr(step);
// var getValue=a/1;
// console.log(attr);
// });
});
</script>
</body>
</html>
I'm very new in the javascript and I want to put the values of 8 labels (text) to an array of 8 numbers, then get the prime numbers of the array, I can make the array and I can set the 8 labels in the html, but I'm not sure with taking that values to the array. If you could help me it will be awesome, thanks!
The code of my solver button:
$('#btn1').click(function () {
var primes = [true, true, true, true, true, true, true, true];
var limit = Math.sqrt(8);
for (var i = 1; i < 8; i++) {
if (primes[i] === true) {
for (var j = i * i; j < 8; j += i) {
primes[j] = false;
}
}
}
for (var i = 1; i < 8; i++) {
if (primes[i] === true) {
console.log(i + " " + primes[i]);
}
}
});
The code of the labels:
<label>1. </label> <input id="input1" type="text"><br>
<label>2. </label> <input id="input2" type="text"><br>
<label>3. </label> <input id="input3" type="text"><br>
<label>4. </label> <input id="input4" type="text"><br>
<label>5. </label> <input id="input5" type="text"><br>
<label>6. </label> <input id="input6" type="text"><br>
<label>7. </label> <input id="input7" type="text"><br>
<label>8. </label> <input id="input8" type="text"><br>
Code to check if number is prime (from: https://stackoverflow.com/a/24094774/1013526):
function isPrime(n) {
// If n is less than 2 or not an integer then by definition cannot be prime.
if (n < 2) {return false}
if (n != Math.round(n)) {return false}
// Now assume that n is prime, we will try to prove that it is not.
var isPrime = true;
// Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {isPrime = false}
}
// Finally return whether n is prime or not.
return isPrime;
}
Code for the solver button click:
$('#btn1').click(function () {
var count = 8; // in case you decide to change this later
var primes = {}; // object instead of array
for (var i = 1; i < count; i++) {
var value = $('#input'+i).val(); // get the input value;
value = parseInt(value); // convert it from string to int.
primes[i] = {};
primes[i].value = value;
primes[i].isPrime = isNan(value) ? false : isPrime(value);
$('#result'+i).text(primes[i].isPrime ? 'Prime' : 'Not Prime');
}
console.dir(primes); // log output to console.
$('#container2').html(JSON.stringify(primes)); // output to container2 as string
});
The code of the labels (modified):
<label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
<label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
<label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
<label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
<label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
<label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
<label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>
If you want to make the output a little more pretty you could do something like this:
var output = '<pre>';
for (var i in primes) {
output += primes[i].value + ': ' + primes[i].isPrime + "\n";
}
output += '</pre>';
$('#container2').html(output);
You don't need to create an array and iterate over each element in the array. Instead, you can just write a function to check whether the passed label is a prime number or not. If it is prime, fill the HTML. I have written my function in PHP but the logic is same for javascript.
function is_prime($number)
{
if ($number==1)
return false;
if ($number==2)
return true;
$sqrt = sqrt($number);
$floor = floor($sqrt);
for ($i=2 ; $i <= $floor ; $i++)
{
if ($number % $i == 0)
{
return false;
}
}
return true;
}
$start = 1;
$labels = 8;
for($i = 1; $i <= $labels; $i++)
{
if(is_prime($i))
{
echo '<label>'.$i.'. </label>'.'<input id="input'. $i.'" type="text" value=" '. $i .'">'.'<br>';
}
}
// output
2. 2
3. 3
5. 5
7. 7
Hope this helps !
Here's my entire HTML:
<script>
$(document).ready(function(){
$('#btn1').click(function () {
var count = 8; // in case you decide to change this later
var primes = {}; // object instead of array
for (var i = 1; i < count; i++) {
var value = $('#input'+i).val(); // get the input value;
value = parseInt(value); // convert it from string to int.
primes.i.value = value;
primes.i.isPrime = isNan(value) ? false : isPrime(value);
$('#result'+i).text(primes.i.isPrime ? 'Prime' : 'Not Prime');
}
$('#container2').html(primes); // log output to console.
});
function isPrime(n) {
// If n is less than 2 or not an integer then by definition cannot be prime.
if (n < 2) {return false}
if (n != Math.round(n)) {return false}
// Now assume that n is prime, we will try to prove that it is not.
var isPrime = true;
// Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {isPrime = false}
}
// Finally return whether n is prime or not.
return isPrime;
}
});
</script>
</head>
<body>
<center><h2>Prime Numbers Calculator.</h2><br></center>
<div class="well">
<div class="container" id="container1">
<div class="col-md-4">
<label>1. </label> <input id="input1" type="text"><span id="result1"></span><br>
<label>2. </label> <input id="input2" type="text"><span id="result2"></span><br>
<label>3. </label> <input id="input3" type="text"><span id="result3"></span><br>
<label>4. </label> <input id="input4" type="text"><span id="result4"></span><br>
<label>5. </label> <input id="input5" type="text"><span id="result5"></span><br>
<label>6. </label> <input id="input6" type="text"><span id="result6"></span><br>
<label>7. </label> <input id="input7" type="text"><span id="result7"></span><br>
<label>8. </label> <input id="input8" type="text"><span id="result8"></span><br>
</div>
<div class="col-md-4">
<div class="container" id="container2">
</div>
</div>
<div class="col-md-4">
<div class="container" id="container3">
</div>
</div>
</div>
</div>
<center><button id="btn1" class="btn btn-primary"> Calculate</button>
<button id="btn2" class="btn btn-primary"> Show</button>
<button id="btn3" class="btn btn-primary"> Sort</button>
<button id="btn4" class="btn btn-primary"> Clean</button></center>
</body>
But still have an issue showing the result in the other container