How to sum a price based on quantity amount - javascript

I am trying to create a input for Quantity (Plus/Minus Buttons) but I can't get it to sum up the price when a different quantity is chosen.
For example, if the item is £2.00 and 2x quantity is chosen then it should display £4.00 instead
Here is what I have so far..
function increaseCount(a, b) {
var input = b.previousElementSibling;
var value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value++;
input.value = value;
}
function decreaseCount(a, b) {
var input = b.nextElementSibling;
var value = parseInt(input.value, 10);
if (value > 1) {
value = isNaN(value) ? 0 : value;
value--;
input.value = value;
}
}
$('#quantity').change(function (event) {
$('#price').html($(this).val() * parseInt($('#price').text(), 10));
});
.counter {
width: 150px;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.counter input {
background:none;
margin:0px 12px;
width:80px;
border:1px solid #0052cc;
line-height:34px;
font-size:20px;
text-align:center;
color:var(--text-color);
appearance:none;
outline:0;
}
.counter span {
background:#0052cc;
display: block;
font-size: 25px;
padding:0 10px;
cursor: pointer;
color:#111;
user-select: none;
}
<div class="counter">
<span class="down" onClick='decreaseCount(event, this)'>-</span>
<input type="text" id="quantity" value="1" name="quantity">
<span class="up" onClick='increaseCount(event, this)'>+</span>
</div>
Price: £<span id="price" value="2.00"></span>2.00

The "updateTotalPrice" function is called from within the "increaseCount", "decreaseCount", and "change" event listeners to ensure that the total price is always up-to-date. The "price" element is used to display the calculated total, which is formatted to two decimal places using the "toFixed" method.
function increaseCount(a, b) {
var input = b.previousElementSibling;
var value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value++;
input.value = value;
updateTotalPrice();
}
function decreaseCount(a, b) {
var input = b.nextElementSibling;
var value = parseInt(input.value, 10);
if (value > 1) {
value = isNaN(value) ? 0 : value;
value--;
input.value = value;
updateTotalPrice();
}
}
function updateTotalPrice() {
var quantity = parseInt($('#quantity').val(), 10);
var price = parseFloat($('#price').attr('value'));
var total = quantity * price;
$('#price').text(total.toFixed(2));
}
$(document).ready(function() {
// set up event listeners
$('#plus-btn').click(function(event) {
increaseCount(event, this);
});
$('#minus-btn').click(function(event) {
decreaseCount(event, this);
});
$('#quantity').change(function(event) {
updateTotalPrice();
});
// update total price on page load
updateTotalPrice();
});
.counter {
width: 150px;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.counter input {
background:none;
margin:0px 12px;
width:80px;
border:1px solid #0052cc;
line-height:34px;
font-size:20px;
text-align:center;
color:var(--text-color);
appearance:none;
outline:0;
}
.counter span {
background:#0052cc;
display: block;
font-size: 25px;
padding:0 10px;
cursor: pointer;
color:#111;
user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter">
<span class="down" onClick='decreaseCount(event, this)'>-</span>
<input type="text" id="quantity" value="1" name="quantity">
<span class="up" onClick='increaseCount(event, this)'>+</span>
</div>
Price: £<span id="price" value="2.00"></span>

You can do it by adding a function that will be called when increase or decrease the quantity to update prices :
function updatePrice(quantity) {
let price = parseFloat($('#price').attr('value') * quantity).toFixed(2);
$('#price').html(price);
}
function increaseCount(a, b) {
var input = b.previousElementSibling;
var value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value++;
input.value = value;
updatePrice(value);
}
function decreaseCount(a, b) {
var input = b.nextElementSibling;
var value = parseInt(input.value, 10);
if (value > 1) {
value = isNaN(value) ? 0 : value;
value--;
input.value = value;
}
updatePrice(value);
}
function updatePrice(quantity) {
let price = parseFloat($('#price').attr('value') * quantity).toFixed(2);
$('#price').html(price);
}
.counter {
width: 150px;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.counter input {
background:none;
margin:0px 12px;
width:80px;
border:1px solid #0052cc;
line-height:34px;
font-size:20px;
text-align:center;
color:var(--text-color);
appearance:none;
outline:0;
}
.counter span {
background:#0052cc;
display: block;
font-size: 25px;
padding:0 10px;
cursor: pointer;
color:#111;
user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter">
<span class="down" onClick='decreaseCount(event, this)'>-</span>
<input type="text" id="quantity" value="1" name="quantity">
<span class="up" onClick='increaseCount(event, this)'>+</span>
</div>
Price: £<span id="price" value="2.00">2.00</span>

Related

how do i access max and can use it in my function?

So at the moment in my checkMaxinput function i wrote my max value was 15 and 100 in backend-benutzer and app-benutzer.
I want the max value to replace it so i dont have to write it manually everytime the max value changes how would i do that? i tried this.max but it didnt work how do i access the max value and can implement that in my function?
var percent = 1; //Standardvalue for yearly
var percentmonthly = 1.2 //Standardvalue for monthly
//diese funktion wird ausgelöst wenn das html-dokument vollstaendig geladen wird
document.addEventListener("DOMContentLoaded", function (event) {
var updatecolor = document.querySelectorAll('.updatecolor');
//anzeige der farbe im range slider
document.querySelectorAll(".updatecolor").forEach(updateinputs =>
updateinputs.addEventListener("input", function () {
var percent = calcPercent(this.value, this.min, this.max);
const bg = getComputedStyle(this).getPropertyValue('--background');
const slider = getComputedStyle(this).getPropertyValue('--slider');
var colorchanger = this.getAttribute('rangecolorid');
var sliderselect = document.querySelector('#' + colorchanger);
sliderselect.setAttribute(
'style',
` background:linear-gradient(to right,${slider},${slider} ${percent}%,${bg} ${percent}%) `
)
})
);
//Initiale Anzeige der Daten
calcSum();
});
//hides when app-benutzer or bürosoftware-benutzer is at 100%
function checkMaxInput(element) {
var hidden = document.getElementById('hiddenMax');
if (hidden) {
this.value == this.max ? (hidden.style.visibility = 'visible') : (hidden.style.visibility = 'hidden')
}
}
//funktion damit der Slider sich beim eingeben vom input field bewegt
function updateUser(val, inputtype) {
if (inputtype == 'Appuserrangecolor') {
document.getElementById('AppInput').value = val;
}
if (inputtype == 'AppInput') {
document.getElementById('Appuserrangecolor').value = val;
}
if (inputtype == 'Backendrangecolor') {
document.getElementById('BackendInput').value = val;
}
if (inputtype == 'BackendInput') {
document.getElementById('Backendrangecolor').value = val;
}
calcSum();
checkMaxInput();
}
//Calculates the percentage of the currentval with the base of a min and max value
function calcPercent(curval, min, max) {
return ((curval - min) / (max - min)) * 100;
}
//Rechnung für die Anzahl von Backend und App-Benutzern
function calcSum() {
}
function checkMaxInput() {
var hidden = document.getElementById("hiddenMax");
if (
document.getElementById("AppInput").value === "100" ||
document.getElementById("BackendInput").value === "15"
) {
hidden.style.visibility = "visible";
} else {
hidden.style.visibility = "hidden";
}
}
html, body {
background-color: rgb(255, 255, 255);
height: 100%;
margin: 0;
}
header{
text-align: center;
font-size: 20px;
}
body, table, select {
font-size: 12px;
}
input[type=range]{
border-radius: 32px;
height: 10px;
cursor: pointer;
}
*, *::before, *::after {
box-sizing: border-box;
}
.grid-container {
display: grid;
grid-template-columns:600px 250px ;
grid-auto-rows: minmax(150px, auto);
justify-items: stretch;
align-items: stretch;
}
.grid-item-1 {
align-self: start;
justify-self: center;
}
.text-grey{
color:grey;
}
.grid-container {
padding: 60px;
width: 100%;
grid-template-columns: 250px 200px;
}
#Backendrangecolor, #Appuserrangecolor, #BackendInput, #AppInput {
--background: rgb(96,125,139,0.33);
--slider: #00ba7a;
background: var(--background);
-webkit-appearance: none;
width: 150px;
}
#Backendrangecolor, #Appuserrangecolor :-moz-range-thumb {
background: purple;
}
.grid-item {
padding: 20px;
padding-top: 15px;
background-color: #f8f8f8;
color: #222;
border: 7px solid rgba(96,125,139,0.33);
}
.grid-item:nth-child(odd) {
background-color: #f8f8f8;
}
.target {
display: none;
}
/* Base styling*/
body {
background-color: #f8f8f8;
max-width: 768px;
margin: 0 auto;
padding: 1em 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a {
text-decoration: none;
}
}
.price-container .text {
width: 80px;
display: inline-block;
text-align: right;
}
.price-container .value {
width: 30px;
display: inline-block;
text-align: left;
}
.button {
text-align: center;
width: 75px;
height: auto;
font-size:8px;
color:#f8f8f8 ;
background-color: rgba(255,167,55,1);
border: rgba(255,167,55,1);
}
<html>
<head>
<title>Document</title>
</head>
<body>
<div class="grid-container">
<div style="width: 270px"class="grid-item">
<header>Preiskalkulator</header>
<div class="slidecontainer">
App-Benutzer: <br>
<input id="Appuserrangecolor" value="0" type="range" rangecolorid="Appuserrangecolor" min="0" max="100" oninput="updateUser(this.value, 'Appuserrangecolor');" class='appuser updatecolor'></input>
<input class='updatecolor' style="width: 30px;border-color: var(--form_border_color);" type="text" id="AppInput" value="0" placeholder="1-100" rangecolorid="Appuserrangecolor" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateUser(this.value, 'AppInput');"><br>
Bürosoftware-Benutzer: <br>
<input id="Backendrangecolor" value="1" type="range" rangecolorid="Backendrangecolor" min="1" max="15" oninput="updateUser(this.value, 'Backendrangecolor'); " class='backenduser updatecolor'></input>
<input class='updatecolor' style="width: 30px;border-color: var(--form_border_color);" type="text" id="BackendInput" rangecolorid="Backendrangecolor" value="1" min="1" max="15" placeholder="1-15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value,); updateUser(this.value, 'BackendInput');"><br>
</div>
<div class="grid-item" style="width: 270px">
<div id="hiddenMax"class="button" style="margin-left: auto;margin-right: auto;margin-top: 10px;">
<button class="button" ><a class="button" target="blank" href="https://solutions.stressfrei.de/kontakt/">Größeres Packet auf Anfrage</a></button>
</div>
</div>
</div>
</body>
</html>
I assume you want to know how to get the max value of your input.
This can be done with the function getAttribute('max').
Documentation of getAttribute
function checkMaxInput(element) {
var hidden = document.getElementById('hiddenMax');
if (hidden) {
element.value == element.getAttribute('max') ? (hidden.style.visibility = 'visible') : (hidden.style.visibility = 'hidden')
}
}

How to make button appear when input reaches max value?

So i want the button to appear when the slider reaches 100% in either one of App-Benutzer or Bürosoftware-Benutzer and when its not at 100% i want it to dissappear.
function checkMaxInput(element) {
var hidden = document.getElementById('hiddenMax');
if (hidden) {
this.value == this.max ? (hidden.style.visibility = 'visible') : (hidden.style.visibility = 'hidden')
}
}
I tried to create a function but i guess i didnt do it right yet.
var percent = 1; //Standardvalue for yearly
var percentmonthly = 1.2 //Standardvalue for monthly
//diese funktion wird ausgelöst wenn das html-dokument vollstaendig geladen wird
document.addEventListener("DOMContentLoaded", function (event) {
var updatecolor = document.querySelectorAll('.updatecolor');
//anzeige der farbe im range slider
document.querySelectorAll(".updatecolor").forEach(updateinputs =>
updateinputs.addEventListener("input", function () {
var percent = calcPercent(this.value, this.min, this.max);
const bg = getComputedStyle(this).getPropertyValue('--background');
const slider = getComputedStyle(this).getPropertyValue('--slider');
var colorchanger = this.getAttribute('rangecolorid');
var sliderselect = document.querySelector('#' + colorchanger);
sliderselect.setAttribute(
'style',
` background:linear-gradient(to right,${slider},${slider} ${percent}%,${bg} ${percent}%) `
)
})
);
//Initiale Anzeige der Daten
calcSum();
});
//hides when app-benutzer or bürosoftware-benutzer is at 100%
function checkMaxInput(element) {
var hidden = document.getElementById('hiddenMax');
if (hidden) {
this.value == this.max ? (hidden.style.visibility = 'visible') : (hidden.style.visibility = 'hidden')
}
}
//funktion damit der Slider sich beim eingeben vom input field bewegt
function updateUser(val, inputtype) {
if (inputtype == 'Appuserrangecolor') {
document.getElementById('AppInput').value = val;
}
if (inputtype == 'AppInput') {
document.getElementById('Appuserrangecolor').value = val;
}
if (inputtype == 'Backendrangecolor') {
document.getElementById('BackendInput').value = val;
}
if (inputtype == 'BackendInput') {
document.getElementById('Backendrangecolor').value = val;
}
calcSum();
}
//Calculates the percentage of the currentval with the base of a min and max value
function calcPercent(curval, min, max) {
return ((curval - min) / (max - min)) * 100;
}
//Rechnung für die Anzahl von Backend und App-Benutzern
function calcSum() {
}
//funktion um preisstaffel zu berechnen
function getPrice(pricemodels, percent, amount) {
for (var key in pricemodels) {
//If key is higher than the selected amount, return the value
if (parseInt(key) >= parseInt(amount)) {
return pricemodels[key] * percent;
}
}
}
html, body {
background-color: rgb(255, 255, 255);
height: 100%;
margin: 0;
}
header{
text-align: center;
font-size: 20px;
}
body, table, select {
font-size: 12px;
}
input[type=range]{
border-radius: 32px;
height: 10px;
cursor: pointer;
}
*, *::before, *::after {
box-sizing: border-box;
}
.grid-container {
display: grid;
grid-template-columns:600px 250px ;
grid-auto-rows: minmax(150px, auto);
justify-items: stretch;
align-items: stretch;
}
.grid-item-1 {
align-self: start;
justify-self: center;
}
.text-grey{
color:grey;
}
.grid-container {
padding: 60px;
width: 100%;
grid-template-columns: 250px 200px;
}
#Backendrangecolor, #Appuserrangecolor, #BackendInput, #AppInput {
--background: rgb(96,125,139,0.33);
--slider: #00ba7a;
background: var(--background);
-webkit-appearance: none;
width: 150px;
}
#Backendrangecolor, #Appuserrangecolor :-moz-range-thumb {
background: purple;
}
.grid-item {
padding: 20px;
padding-top: 15px;
background-color: #f8f8f8;
color: #222;
border: 7px solid rgba(96,125,139,0.33);
}
.grid-item:nth-child(odd) {
background-color: #f8f8f8;
}
.target {
display: none;
}
/* Base styling*/
body {
background-color: #f8f8f8;
max-width: 768px;
margin: 0 auto;
padding: 1em 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
a {
text-decoration: none;
}
}
.price-container .text {
width: 80px;
display: inline-block;
text-align: right;
}
.price-container .value {
width: 30px;
display: inline-block;
text-align: left;
}
.button {
text-align: center;
width: 75px;
height: auto;
font-size:8px;
color:#f8f8f8 ;
background-color: rgba(255,167,55,1);
border: rgba(255,167,55,1);
}
<html>
<head>
<link rel="stylesheet" href="styles.css">
<script src="./app.js"></script>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="grid-container">
<div style="width: 270px"class="grid-item">
<header>Preiskalkulator</header>
<div class="slidecontainer">
App-Benutzer: <br>
<input id="Appuserrangecolor" value="0" type="range" rangecolorid="Appuserrangecolor" min="0" max="100" oninput="updateUser(this.value, 'Appuserrangecolor');" class='appuser updatecolor'></input>
<input class='updatecolor' style="width: 30px;border-color: var(--form_border_color);" type="text" id="AppInput" value="0" placeholder="1-100" rangecolorid="Appuserrangecolor" min="0" max="100" oninput="this.value = this.value > 100 ? 100 : Math.abs(this.value); updateUser(this.value, 'AppInput');"><br>
Bürosoftware-Benutzer: <br>
<input id="Backendrangecolor" value="1" type="range" rangecolorid="Backendrangecolor" min="1" max="15" oninput="updateUser(this.value, 'Backendrangecolor'); " class='backenduser updatecolor'></input>
<input class='updatecolor' style="width: 30px;border-color: var(--form_border_color);" type="text" id="BackendInput" rangecolorid="Backendrangecolor" value="1" min="1" max="15" placeholder="1-15" oninput="this.value = this.value > 15 ? 15 : Math.abs(this.value,); updateUser(this.value, 'BackendInput');"><br>
</div>
<div class="grid-item" style="width: 270px">
<div id="hiddenMax"class="button" style="margin-left: auto;margin-right: auto;margin-top: 10px;">
<button class="button" ><a class="button" target="blank" href="https://solutions.stressfrei.de/kontakt/">Größeres Packet auf Anfrage</a></button>
</div>
</div>
</div>
</body>
</html>
You can rewrite checkMaxInput first
Since updateUser will sync range input and text input
We can simply pick just two input that represent App-Benutzer and Bürosoftware-Benutzer as condition
If slider reachs 100% means that App-Benutzer's value will be 100 and Bürosoftware-Benutzer's value will be 15
So, we can rewrite checkMaxInput like below:
function checkMaxInput() {
var hidden = document.getElementById("hiddenMax");
if (
document.getElementById("AppInput").value === "100" ||
document.getElementById("BackendInput").value === "15"
) {
hidden.style.visibility = "visible";
} else {
hidden.style.visibility = "hidden";
}
}
Then, you can call it after updateUser finished task to sync input's value
For example
function updateUser(val, inputtype) {
if (inputtype == "Appuserrangecolor") {
document.getElementById("AppInput").value = val;
}
if (inputtype == "AppInput") {
document.getElementById("Appuserrangecolor").value = val;
}
if (inputtype == "Backendrangecolor") {
document.getElementById("BackendInput").value = val;
}
if (inputtype == "BackendInput") {
document.getElementById("Backendrangecolor").value = val;
}
calcSum();
checkMaxInput();
}
Finally, if you want the button was hidden initially
You have to add these two line in your DOMContentLoaded's callback function
var hidden = document.getElementById("hiddenMax");
hidden.style.visibility = "hidden";
Or simply write style visibility: hidden; at #hiddenMax in HTML
I suggest to use a pure function to check if the element needs to be shown or not, something like this
function checkMaxInput(element) {
var attrs = element.attributes;
return element.value == attrs.max.nodeValue;
}
function updateUser(element, inputtype) {
var hidden = document.getElementById('hiddenMax');
checkMaxInput(element) ?
hidden.style.visibility = 'visible' :
hidden.style.visibility = 'hidden';
}
see a simplified example here https://jsbin.com/cucemujiyo/1/edit?html,css,js,output

Add or subsctract function from total value

So I want to add or substract a value from total, based on which div is clicked (minus or plus sign). A counter also shows how much the value is (this I have working). So i want to calculate the total from which items are clicked.
My code for now:
var minExtras = document.querySelectorAll(".extra-min");
var plusExtras = document.querySelectorAll(".extra-plus");
var totalPrice = document.getElementById("totalPrice");
totalPrice.innerHTML = "Totaalprijs: € ";
Array.prototype.forEach.call(minExtras, function (minExtra) {
minExtra.addEventListener('click', function() {
var currentCount = minExtra.parentElement.querySelector('.count').innerText;
if (currentCount !== "1") {
var newCount = currentCount - 1;
minExtra.parentElement.querySelector('.count').innerText = newCount;
}
var colorMin = minExtra.parentElement.querySelector('.extra-min');
if (newCount === 1) {
colorMin.setAttribute("class", "change-extra min extra-min");
}
var extraPrice = minExtra.parentElement.querySelector('.extraPrice').innerText;
var extraPriceValue = extraPrice * newCount;
calculateMin(extraPriceValue);
})
});
Array.prototype.forEach.call(plusExtras, function (plusExtra) {
plusExtra.addEventListener('click', function() {
var currentCount = plusExtra.parentElement.querySelector('.count').innerText;
var newCount = +currentCount + +1;
plusExtra.parentElement.querySelector('.count').innerText = newCount;
var colorMin = plusExtra.parentElement.querySelector('.extra-min');
if (newCount !== 1) {
colorMin.setAttribute("class", "change-extra min extra-min color");
} else {
colorMin.setAttribute("class", "change-extra min extra-min");
}
var extraPrice = plusExtra.parentElement.querySelector('.extraPrice').innerText;
var extraPriceValue = extraPrice * newCount;
calculatePlus(extraPriceValue);
})
});
function calculatePlus(price) {
//function here
totalPrice.innerHTML = calculatedPrice;
}
function calculateMin(price) {
//function here
totalPrice.innerHTML = calculatedPrice;
}
.item {
margin-bottom: 10px;
width: 120px;
padding: 20px;
border: 1px solid #C5C5C5;
}
.show-extra-container {
display: -webkit-flex;
display: flex;
-justify-content: flex-start;
justify-content: flex-start;
-webkit-align-items: center;
align-items: center;
}
.extra-aantal {
padding: 0px 14px;
font-weight: 700;
font-size: 16px;
}
.change-extra {
font-weight: 700;
font-size: 28px;
color: #EC008C;
cursor: pointer;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
.change-extra.min {
background-color: #C5C5C5;
width: 14px;
height: 3px;
margin-top: 3px;
border-radius: 4px;
}
.change-extra.min.color {
background-color: #EC008C;
}
#totalPrice {
font-weight: 700;
}
<div id="showextra1" class="item">
<label class="col-form-label">Aantal personen</label>
<div class="show-extra-container">
<span class="extraPrice" style="display: none;">10</span>
<div class="change-extra min extra-min"></div>
<div class="extra-aantal count">1</div>
<div class="change-extra plus extra-plus">+</div>
</div>
</div>
<div id="showextra2" class="item">
<label class="col-form-label">Aantal personen</label>
<div class="show-extra-container">
<span class="extraPrice" style="display: none;">5</span>
<div class="change-extra min extra-min"></div>
<div class="extra-aantal count">1</div>
<div class="change-extra plus extra-plus">+</div>
</div>
</div>
<div class="item">
<div id="totalPrice"></div>
</div>
So this code works pretty good for what I need. Now I just need to calculate a totalprice and set the innerHTML of totalPrice. I was thinking to use a seperate function calculateMin() and calculatePlus(). However I have no idea how to write this function that calculates the total. Does anyone know how to do this?
Try like this:
var minExtras = document.querySelectorAll(".extra-min");
var plusExtras = document.querySelectorAll(".extra-plus");
var totalPrice = document.getElementById("totalPrice");
totalPrice.innerHTML = "Totaalprijs: € ";
var calculatedPrice = 0;
//count initial price
Array.prototype.forEach.call(document.querySelectorAll('.show-extra-container'), function(container) {
calculatedPrice += parseInt(container.querySelector('.count').innerText) * parseFloat(container.querySelector('.extraPrice').innerText);
});
totalPrice.innerHTML = "Totaalprijs: € " + calculatedPrice;
Array.prototype.forEach.call(minExtras, function(minExtra) {
minExtra.addEventListener('click', function() {
var currentCount = minExtra.parentElement.querySelector('.count').innerText;
if (currentCount !== "1") {
var newCount = currentCount - 1;
minExtra.parentElement.querySelector('.count').innerText = newCount;
} else {
return;
};
var colorMin = minExtra.parentElement.querySelector('.extra-min');
if (newCount === 1) {
colorMin.setAttribute("class", "change-extra min extra-min");
}
var extraPrice = minExtra.parentElement.querySelector('.extraPrice').innerText;
//calculateMin: -1
calculatedPrice -= parseFloat(extraPrice);
totalPrice.innerHTML = "Totaalprijs: € " + calculatedPrice;
})
});
Array.prototype.forEach.call(plusExtras, function(plusExtra) {
plusExtra.addEventListener('click', function() {
var currentCount = plusExtra.parentElement.querySelector('.count').innerText;
var newCount = +currentCount + +1;
plusExtra.parentElement.querySelector('.count').innerText = newCount;
var colorMin = plusExtra.parentElement.querySelector('.extra-min');
if (newCount !== 1) {
colorMin.setAttribute("class", "change-extra min extra-min color");
} else {
colorMin.setAttribute("class", "change-extra min extra-min");
}
var extraPrice = plusExtra.parentElement.querySelector('.extraPrice').innerText;
//calculatePlus: +1
calculatedPrice += parseFloat(extraPrice);
totalPrice.innerHTML = "Totaalprijs: € " + calculatedPrice;
})
});
.item {
margin-bottom: 10px;
width: 120px;
padding: 20px;
border: 1px solid #C5C5C5;
}
.show-extra-container {
display: -webkit-flex;
display: flex;
-justify-content: flex-start;
justify-content: flex-start;
-webkit-align-items: center;
align-items: center;
}
.extra-aantal {
padding: 0px 14px;
font-weight: 700;
font-size: 16px;
}
.change-extra {
font-weight: 700;
font-size: 28px;
color: #EC008C;
cursor: pointer;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
}
.change-extra.min {
background-color: #C5C5C5;
width: 14px;
height: 3px;
margin-top: 3px;
border-radius: 4px;
}
.change-extra.min.color {
background-color: #EC008C;
}
#totalPrice {
font-weight: 700;
}
<div id="showextra1" class="item">
<label class="col-form-label">Aantal personen</label>
<div class="show-extra-container">
<span class="extraPrice" style="display: none;">10</span>
<div class="change-extra min extra-min"></div>
<div class="extra-aantal count">1</div>
<div class="change-extra plus extra-plus">+</div>
</div>
</div>
<div id="showextra2" class="item">
<label class="col-form-label">Aantal personen</label>
<div class="show-extra-container">
<span class="extraPrice" style="display: none;">5</span>
<div class="change-extra min extra-min"></div>
<div class="extra-aantal count">1</div>
<div class="change-extra plus extra-plus">+</div>
</div>
</div>
<div class="item">
<div id="totalPrice"></div>
</div>
Calculate the initial calculatedPrice (.count * .extraPrice) for each item
When clicking - or +, simply add or remove one .extraPrice for that item
return from minExtra listener if the count is already at the minimum of 1.

If..,else.. in javascript

I am trying to solve my problem with if-else in Javascript.
I would highly appreciate your help.
I wanted to filter the name via gender, also safe the keys - woman / man to local storage.
But I can not find out how to make if-else clause.
Can someone help me?
There is also the link:
https://drive.google.com/file/d/1RNJxbiU_DsFTCqGJWgxpepCgdOhGuzIj/view?usp=sharing
Thanks a lot, it means world to me, I am new here. :-)
$(document).ready(function() {
function displayName() {
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//find list
let nameUl = $('#list_2');
nameUl.empty(); //.html('')
//making list
$.each(safeName, function(key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//remove link
let jmenoRemoveLink = $('x');
jmenoRemoveLink.click(function(e) {
e.preventDefault();
//name
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
//remove
safeName.splice(key, 1);
//safe name
localStorage.setItem('woman', JSON.stringify(safeName));
//display name
displayName();
});
nameLi.append(jmenoRemoveLink);
nameUl.append(nameLi);
});
}
$('#formular').submit(function(e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
if (zadaneJmeno) {
//safe
let safeNameVal = localStorage.getItem('woman');
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem('woman', JSON.stringify(safeName)); /// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function() {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="formular">
<label for="name">Enter the name</label>
<input type="text" id="name" required />
<label for="section">Gender</label>
<select name="selectSection" id="section" required>
<option value="">---</option>
<option value="man" id="man">man</option>
<option value="woman" id="woman">woman</option>
</select>
<input type="submit" value="add" />
</form>
<button id="removeAll">Remove</button>
<div id="man_div">
<h1>man:</h1>
<ul id="list"></ul>
</div>
<div id="woman_div">
<h1>woman:</h1>
<ul id="list_2"></ul>
</div>
I made a number of changes to your script, do note that as I am solving your problem, I removed the 'x' function on click because it is too verbose to read while solving your problem, do add it back later, and make sure you remove from the correct localStorage.
$(document).ready(function () {
function displayName() {
//Separate the local storage into man and woman keys
let manSafeNameVal = localStorage.getItem('man');
let manSafeName;
let womanSafeNameVal = localStorage.getItem('woman');
let womanSafeName
if (manSafeNameVal) {
manSafeName = JSON.parse(manSafeNameVal);
} else {
manSafeName = [];
}
if (womanSafeNameVal) {
womanSafeName = JSON.parse(womanSafeNameVal);
} else {
womanSafeName = [];
}
//find list
//Use list and list_2 to display
let manUl = $('#list');
let womanUl = $('#list_2');
manUl.empty(); //.html('')
womanUl.empty();
//list for man
$.each(manSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//do add back your 'x' remove here, because it is too verbose to read when I am trying to read the code
manUl.append(nameLi);
});
//list for woman
$.each(womanSafeName, function (key, name) {
let nameLi = $('<li></li>');
nameLi.text(name);
//Also here, the 'x' for woman list
womanUl.append(nameLi);
});
}
$('#formular').submit(function (e) {
e.preventDefault();
let zadaneJmeno = $('#name').val();
//get the selected gender, either man or woman
let gender = $('#section').val();
console.log(gender);
console.log(zadaneJmeno);
if (zadaneJmeno && gender !== "") {
//safe into the localStorage of selected gender
let safeNameVal = localStorage.getItem(gender);
let safeName;
if (safeNameVal) {
safeName = JSON.parse(safeNameVal);
} else {
safeName = [];
}
safeName.push(zadaneJmeno);
localStorage.setItem(gender, JSON.stringify(safeName));/// ["Tom"]
//list
displayName();
$('#name').val('');
} else {
// alert
alert('please enter the name"');
$('#name').focus();
}
});
$('#removeAll').click(function () {
localStorage.setItem('woman', '[]'); ///localStorage.setItem('woman', JSON.stringify([]));
displayName();
});
displayName();
});
const katText = document.getElementById('txtKategorie');
const oText=document.querySelector('input[homework="homework"]');
// selektor tlačítka uložit úkol
const oBttn=document.querySelector('input[type="submit"]');
// selektor tlačítka na odstranění všech úkolů z kategorie
const oDelete=document.querySelector('button#removeAll');
const createlist=function(){
let parent=document.getElementById('lists');
Object.keys(localStorage).forEach(function (key) {
let category = key;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// odstranění určité položky
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( homework=>{
addlistitem(homework,store);
})
});
}
//na klik oznaci div
function oznacDiv() {
if (oBttn.disabled) oBttn.disabled = false;
document.querySelectorAll('div.active').forEach(div => {
div.classList.remove('active')
});
document.querySelector('div#' + this.id).classList.add('active')
}
const clearstoreitems=function(category){
localStorage.setItem( category, JSON.stringify([]) );
document.querySelector( 'div#' + category ).querySelector('ul').innerHTML='';
};
const deleteitem=function(e){
let parent=e.target.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(category));
if( data!=null )data.splice(data.indexOf(homework),1);
localStorage.setItem(category,JSON.stringify(data));
};
const addlistitem=function(homework,category){
let p=document.createElement('button');
p.innerHTML=' Uprava';
p.onclick =function(){
editWorking(li);
}
let a=document.createElement('a');
a.href='#';
a.innerHTML=' Hotovo';
let li=document.createElement('li');
li.value=homework;
li.textContent=homework;
li.dataset.homework=homework;
li.dataset.category=category;
li.appendChild( a );
li.appendChild(p);
document.querySelector( 'div#' + category ).querySelector('ul').appendChild( li );
};
function editWorking(e){
let editValue = prompt('Přejete si upravit úkol?', e.firstChild.nodeValue);
e.firstChild.nodeValue = editValue;
let parent=e.parentNode;
let homework=parent.dataset.homework;
let category=parent.dataset.category;
addlistitem(editValue,category);
addstoreitem(editValue,category);
}
const addstoreitem=function(homework,category){
let data=localStorage.getItem( category );
if( data!=null ){
let json=JSON.parse( data );
json.push(homework);
data=JSON.stringify(json);
}
else
{
data=JSON.stringify([homework]);
}
localStorage.setItem( category, data );
};
//prida novej div s kategorii a poznamkou
const addNewItemList = function () {
let parent = document.getElementById('lists');
let category = katText.value;
let div = document.createElement('div');
div.id = category;
let h1 = document.createElement('h1');
h1.textContent = category;
let ul = document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
div.onclick = oznacDiv;
parent.appendChild(div);
parent.querySelectorAll('div').forEach(div => {
div.addEventListener('click', function (e) {
// odstranění určité položky
if (e.target != e.currentTarget && e.target.tagName == 'A') deleteitem(e);
});
// při načtení stránky načíst úkoly z localStorage a vytvoření listu
// podmmínka -- pokud není úložiště prázdné
let store = div.id;
if (localStorage.getItem(store) != null) JSON.parse(localStorage.getItem(store)).forEach(homework => {
addlistitem(homework, store);
})
});
}
oBttn.addEventListener('click',function(e){
e.preventDefault();
if (oText.value != '') {
if (katText.value != '') {
if (document.querySelector('div#' + katText.value) == null) {
addNewItemList()
}
addlistitem(oText.value, katText.value);
addstoreitem(oText.value, katText.value);
oText.value = '';
return true;
} else {
alert('Zadejte kategorii prosím...');
}
} else {
alert('Zadejte úkol prosím...');
}
});
// vymazat, resetovat pole
oDelete.addEventListener('click', function (e) {
document.querySelectorAll('div.active').forEach(div => {
//clearstoreitems(document.querySelectorAll('div.active').id);
clearstoreitems(div.id);
//div.classList.remove('active')
});
});
createlist();
#charset "UTF-8";
/* CSS Document */
#import url('https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap');
*{
padding: 100;
margin: 100;
box-sizing: border-box;
font-family: 'Poppins', sans-serif;
}
/**styly pro tělo celé aplikace **/
body{
background: rgb(131,58,180);
background: linear-gradient(90deg, rgba(131,58,180,1) 0%, rgba(253,29,29,1) 50%, rgba(252,176,69,1) 100%);
/* background: linear-gradient(139deg, rgba(193,62,62,1) 0%, rgba(230,179,50,1) 100%);
background-image: url("pozadi.png");*/
overflow-x: hidden;
background-repeat: no-repeat;
background-size: cover;
background-position: center;
background-attachment: fixed;
height: 100%;
}
.weather{
width: 100%;
margin: 20px;
padding: 30px;
}
/** pomohla jsem si tady https://the-echoplex.net/flexyboxes/ **/
/**
.flex-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-justify-content: flex-start;
-ms-flex-pack: start;
justify-content: flex-start;
-webkit-align-content: center;
-ms-flex-line-pack: center;
align-content: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center;
}
.flex-item:nth-child(1) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 1 auto;
-ms-flex: 0 1 auto;
flex: 0 1 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
.flex-item:nth-child(2) {
-webkit-order: 0;
-ms-flex-order: 0;
order: 0;
-webkit-flex: 0 100 auto;
-ms-flex: 0 100 auto;
flex: 0 100 auto;
-webkit-align-self: auto;
-ms-flex-item-align: auto;
align-self: auto;
}
**/
/**nadpis aplikace **/
#nadpis {
/** margin: auto;
width: 50%;
padding: 5px; **/
text-align: center;
font-size: 40px;
}
.predpoved {
/** width: 30%; **/
border-radius: 15px 50px;
border:4px solid white;
background: black;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
margin:0 auto;
height: 10%;
width:60%;
padding: 0 auto;
}
.nadpis_1{
font-size: 50px;
color:white;
font:bold;
}
label{
color:white;
font:oblique;
text-transform:inherit;
}
#lists > div{
padding:1rem;
margin:1rem auto;
border-radius: 15px 50px;
border:4px solid white;
margin-left: 30px;
margin-right: 30px;
-webkit-box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
box-shadow: 7px 8px 6px 0px rgba(0,0,0,0.52);
}
.active{
background: linear-gradient(90deg, rgba(252,176,69,1) 0%, rgba(253,29,29,1) 50%, rgba(131,58,180,1)100%);
}
h1{
text-transform:capitalize;
color:white;
}
ul{
list-style: square;
}
ul li{
color:white;
margin-top: 40px;
font-size: 20px;
}
ul a {
color:white;
font:oblique;
padding: 10px;
margin:10px;
margin-left:100px;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
ul a:hover {
color:white;
font:oblique;
background:rgba(252,176,69,1);
padding: 10px;
margin:10px;
margin-left:100px;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
}
form{
color: white;
padding: 20px;
width: 600px;
margin: 0 auto;
height: auto;
}
#removeAll{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding:10px;
margin-left: 30px;
margin-right: 30px;
}
#removeAll:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
margin-left: 30px;
margin-right: 30px;
}
#refresh{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#refresh:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
#safe{
color:white;
font:oblique;
background: black;
border-radius: 15px ;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
margin: 0 auto;
height: auto;
padding: 10px;
}
#safe:hover {
color:white;
font:oblique;
background: red;
border:1px solid white;
text-decoration: none;
text-transform: uppercase;
padding:10px;
margin: 0 auto;
height: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Deadline</title>
<link rel="stylesheet" href="style.css">
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="flex-container">
<div id="nadpis">
<h1>Deadline</h1>
<form>
<label for="txtHomework">Your homework.. </label>
<input type="text" id="txtHomework" homework="homework" required />
<label for="txtKategorie">Category</label>
<input type="text" id="txtKategorie" kategorie="valKategorie" required />
<!--<select name="selectSection" required>
<option selected hidden disabled>---</option>
<option value="škola">Škola</option>
<option value="Práce">Práce</option>
<option value="Doma">Doma</option>
<option value="Jiné">Jiné</option>
</select>-->
<!--</label>-->
<!-- tlačítko uložit je nedostupné dokud nevybereme kategorii a nezapíšeme úkol -->
<input id ="safe" type="submit" value="Uložit" />
</form>
<div id="lists"></div>
<button id="removeAll">Vyčistit kategorii</button>
I know you already have a solution but I offer an alternative, in vanilla Javascript rather than jQuery, that splits the names according to gender - assigns them to individual areas in localStorage based upon gender and has the functionality to remove individual items from the store. Any items stored in any of the generated stores will be used to populate the HTML lists on page load. I don't use jQuery which is why I wrote this in plain js - no doubt you can cherrypick things from it that might be useful - I hope that it is useful anyway.
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Gender splitter</title>
<style>
#lists > div{
padding:1rem;
margin:1rem auto;
border:1px dotted gray;
}
.active{
background:whitesmoke
}
h1{text-transform:capitalize}
</style>
</head>
<body>
<form>
<label>Enter the name
<input type='text' name='name' required />
</label>
<label>Gender
<select name='selectSection' required>
<option selected hidden disabled>---
<option value='male'>Male
<option value='female'>Female
<option value='teapot'>Teapot
<option value='crocodile'>Crocodile
</select>
</label>
<!-- initially disabled to prevent adding when no gender is selected -->
<input type='submit' value='add' disabled />
</form>
<button id='removeAll'>Remove</button>
<div id='lists'></div>
<script>
const oSelect=document.querySelector('select[name="selectSection"]');
const oText=document.querySelector('input[name="name"]');
const oBttn=document.querySelector('input[type="submit"]');
const oDelete=document.querySelector('button#removeAll');
// generate the necessary HTML nodes to display names/genders based
// upon the options in the select menu.
const createlist=function(){
let parent=document.getElementById('lists');
oSelect.querySelectorAll('option').forEach( option=>{
if( option.value !== oSelect.childNodes[1].value ){
let gender=option.value;
let div=document.createElement('div');
div.id=gender;
let h1=document.createElement('h1');
h1.textContent=gender;
let ul=document.createElement('ul');
div.appendChild(h1);
div.appendChild(ul);
parent.appendChild( div );
}
});
parent.querySelectorAll('div').forEach( div=>{
div.addEventListener('click',function(e){
// delete specific item from the store
if( e.target!=e.currentTarget && e.target.tagName=='A') deleteitem( e );
});
// load any names from the store on page load and recreate the lists
let store=div.id;
if( localStorage.getItem(store)!=null )JSON.parse( localStorage.getItem( store ) ).forEach( name=>{
addlistitem(name,store);
})
});
}
// erase store content by gender and clear html list display
const clearstoreitems=function(gender){
localStorage.setItem( gender, JSON.stringify([]) );
document.querySelector( 'div#' + gender ).querySelector('ul').innerHTML='';
};
// delete specific item from particular store
const deleteitem=function(e){
let parent=e.target.parentNode;
let name=parent.dataset.name;
let gender=parent.dataset.gender;
parent.parentNode.removeChild(parent);
let data=JSON.parse(localStorage.getItem(gender));
if( data!=null )data.splice(data.indexOf(name),1);
localStorage.setItem(gender,JSON.stringify(data));
};
// add new item to HTML list based upon gender
const addlistitem=function(name,gender){
let a=document.createElement('a');
a.href='#';
a.innerHTML='X';
let li=document.createElement('li');
li.value=name;
li.textContent=name;
li.dataset.name=name;
li.dataset.gender=gender;
li.appendChild( a );
document.querySelector( 'div#' + gender ).querySelector('ul').appendChild( li );
};
// add new name to the localStorage in gender specific named store
const addstoreitem=function(name,gender){
let data=localStorage.getItem( gender );
if( data!=null ){
let json=JSON.parse( data );
json.push(name);
data=JSON.stringify(json);
} else { data=JSON.stringify([name]); }
localStorage.setItem( gender, data );
};
// Add new item listener
oBttn.addEventListener('click',function(e){
e.preventDefault();
if( oText.value!='' ){
addlistitem(oText.value,oSelect.value);
addstoreitem(oText.value,oSelect.value);
oText.value='';
return true;
}
alert('Name please...');
});
oSelect.addEventListener('change',function(e){
// ensure the "Add" button is enabled
if( oBttn.disabled )oBttn.disabled=false;
document.querySelectorAll('div.active').forEach( div=>{
div.classList.remove('active')
});
// assign a class to visually identify which gender is selected
document.querySelector( 'div#' + this.value ).classList.add('active')
});
// erase this entire store - reset to empty array
oDelete.addEventListener('click',function(e){
clearstoreitems(oSelect.value);
});
createlist();
</script>
</body>
</html>

how to get variable value for java script from input tag in html

var a = document.f1.getElementsByName('num1');
var b = document.f1.getElementsByName('num2');
function add() {
alert('The sum is ' + parseInt(a) + parseInt(b));
};
body {
background-color: #333333;
color: #e6e6e6;
font-family: 'Calibri', sans-serif;
font-size: 100%;
margin: 0 auto;
}
.addition {
margin-top: 10%;
margin-left: 10%;
margin-right: 10%;
text-align: center;
display: table;
}
.addition input {
background-color: #8585ef;
border: 3px solid;
border-color: #2f2fef;
border-radius: 1em;
color: #ffffff;
display: table-column;
padding: .6em;
}
<form class="addition" name="f1">
<input type="number" name="num1" min="0"> +
<input type="number" name="num2" min="0">
<input style="margin-left:.3em;" type="button" name="Add" value="Add" onclick="add();">
</form>
On clicking the add button the alert does not dispay the sum it displays string and undefine variables. How can I fix this, please help with the variable diclaration.
There are many way to get value from input. You can use id, class and etc.
In JavaScript to get value from id you have to write down:
var yourValue = document.getElementById("val1");
alert(yourValue.value);
To get value from class you have to write down:
var yourValue = document.getElementsByClassName("val1");
for (var i = 0; i < yourValue.length; ++i){
alert(yourValue[i].value);
}
To get value from name you have to write down:
var yourValue = document.getElementsByName("val1");
for (var i = 0; i < yourValue.length; ++i)
{
alert(yourValue[i].name); // to get current name's name
alert(yourValue[i].value); // to get val1 value
}
/*
// you need new values every time so place them inside of the function
var a = document.f1.getElementsByName('num1');
var b = document.f1.getElementsByName('num2');
function add() {
alert('The sum is ' + praseInt(a) + praseInt(b));
// plus sign concatenate and transforms all into string
so you need sum the arguments and THEN + it to the string
};*/
// don't use inline functions, use event listeners
document.getElementsByName('Add')[0].addEventListener('click', add)
function add() {
var a = document.getElementsByName('num1')[0].value;
var b = document.getElementsByName('num2')[0].value;
alert('The sum is ' + (parseInt(a) + parseInt(b)));
};
body {
background-color: #333333;
color: #e6e6e6;
font-family: 'Calibri', sans-serif;
font-size: 100%;
margin: 0 auto;
}
.addition {
margin-top: 10%;
margin-left: 10%;
margin-right: 10%;
text-align: center;
display: table;
}
.addition input {
background-color: #8585ef;
border: 3px solid;
border-color: #2f2fef;
border-radius: 1em;
color: #ffffff;
display: table-column;
padding: .6em;
}
<form class="addition" name="f1">
<input type="number" name="num1" min="0"> +
<input type="number" name="num2" min="0">
<input style="margin-left:.3em;" type="button" name="Add" value="Add">
</form>
There seems to be a spelling mistake in parseInt in the alert call.
var a = document.f1.getElementsByName('num1');
var b = document.f1.getElementsByName('num2');
function add() {
alert('The sum is ' + praseInt(a) + praseInt(b)); // <= Change praseInt to parseInt
};
Right Way:
var a = document.f1.getElementsByName('num1').value;
var b = document.f1.getElementsByName('num2').value;
alert('num1 is ' + a);
alert('num2 is ' + b);
function add() {
alert('The sum is ' + (parseInt(a) + parseInt(b)));
};

Categories