How do i automatically display every time I input number and calculate it.
Then the pick button will trigger to calculate the price, my base price would be 100. so if its 2 layers it will be 200 ,
<br> Layer <input type="number" min="1" id="cake_layer" name="cake_layer" /> <!-- onchange="updateTotal()" -->
<input type="button" value="Pick" id="choose" />
<br>
Layer inputed <div class="layer_display"> </div>
<br>
Layer Amount <div class="layer_amt"> </div>
I really need help. thank you !!!
Is this what you want to do?
var cakeLayer = document.getElementById("cake_layer"),
price = 100,
layerDisplay = document.getElementsByClassName("layer_display")[0],
layerAmt = document.getElementsByClassName("layer_amt")[0];
cakeLayer.onchange = function(event) {
var amount = this.value || 0,
totalPrice = amount * price;
layerDisplay.innerText = totalPrice;
layerAmt.innerText = amount;
}
<input type="number" min="1" id="cake_layer" name="cake_layer" />
<!-- onchange="updateTotal()" -->
<input type="button" value="Pick" id="choose" />
<br> total price
<div class="layer_display"> </div>
<br> Layer Amount
<div class="layer_amt"> </div>
You can achieve this by using JavaScript or jQuery. That's the only way to manipulate the DOM.
See this working jsfiddle I made:
https://jsfiddle.net/jw6q53fz/1/
HMTL
<div>
<label for="cake_layer">Layer</label>
<input type="number" class="cake_layer" name="cake_layer" id="cake_layer"/>
<button id="choose">Pick</button>
</div>
<div>
<p>Layer inputed: <span class="layer_display"> </span></p>
<p>Layer Amount: <span class="layer_amt"> </span></p>
</div>
jQuery
$('#choose').on('click', function(){
var cakeLayerValue = $('#cake_layer').val();
$('.layer_display').html(cakeLayerValue);
$('.layer_amt').html(cakeLayerValue * 100);
});
Related
I am making a mortgage calculator and am trying to clear all the inputs when the clear button is presses. I can't seem to get it to work. Below is my html and JavaScript code, I have also tried setting the inputs = null and that didn't work.
HTML:
<div class="calculator">
<h1>Mortgage Calculator</h1>
<div class="input-container">
<label for="Loan-amount">Total Loan Amount</label>
<input type="number" name="Loan-amount" id="total" min="0">
</div>
<div class="input-container">
<label for="down-payment">Down payment</label>
<input type="number" name="Loan-amount" id="down" min="0">
</div>
<div class="input-container">
<label for="interest-rate">Interest rate %</label>
<input type="number" name="interest-rate" id="interest" min="0">
</div>
<div class="input-container">
<label for="loan-term">Loan Term (in years)</label>
<input type="number" name="loan-term" id="duration" min="0">
</div>
<div class="answer">
<h2>Estimated payment:</h2>
<p id="paragraph-value"></p>
</div>
<div class="button-container">
<button id="submitBtn">Calculate</button>
<button id="clearBtn">Clear</button>
</div>
<p id="alert"></p>
</div>
JavaScript:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
let total = document.getElementById("total").value;
let interest = document.querySelector("#interest").value;
let duration = document.querySelector("#duration").value;
let downPayment = document.querySelector("#down").value;
total = "";
interest = "";
duration = "";
downPayment = "";
});
You're not setting a value to the inputs, you're just over-writing the value of a varable:
total = "";
To set the value of the input, you'd set the .value property on the input:
document.getElementById("total").value = "";
For example:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
document.getElementById("total").value = "";
});
<input type="number" id="total" />
<button id="clearBtn">Reset</button>
At a more generic level, you seem to be confused about the difference between these two things:
var total = document.getElementById("total").value;
total = "";
and:
var total = document.getElementById("total");
total.value = "";
In the first case the variable holds a copy of the value itself, and you're re-assigning the variable to a new value. This does nothing to the element.
But in the second case the variable holds a reference to the element, and you're updating a property on that element.
I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp
I am trying to get two divs to act as checkboxes (so that users can select 0 or all) that will influence hidden input values for a total that starts at 0. I am targetting the clicked divs by toggling a bootstrap color class to show user which has been chosen and - based on that class - add values to the hidden total input values below. I can get the totals to change outright, but I am trying to add to and subtract from the totals based on what is clicked/unclicked. Right now my code is returning an "Uncaught TypeError: Cannot set property 'value' of null". Any help you can give will be greatly appreciated!
$(document).ready(function() {
$('.select-class').on('click', function() {
//toggle clicked divs to show what's been selected
$(this).toggleClass('color');
//add values to total(0) if divs are clicked (have color class)
if (this.classList.contains('color')) {
//add1:
var addTotal1 = Number(document.getElementsByName('total1').value);
var addSingle1 = Number(document.getElementById(this.id.toString() + 'add1').value);
addTotal1 += addSingle1;
document.getElementById('totaladd1').value = addTotal1.toString();
//add2:
var addTotal2 = Number(document.getElementsByName('total2').value);
var addSingle2 = Number(document.getElementById(this.id.toString() + 'add2').value);
addTotal2 += addSingle2;
document.getElementById('totaladd2').value = addTotal2.toString();
//add3:
var addTotal3 = Number(document.getElementsByName('total3').value);
var addSingle3 = Number(document.getElementById(this.id.toString() + 'add3').value);
addTotal3 += addSingle3;
document.getElementById('totaladd3').value = addTotal3.toString();
}
//Subtract values if divs are unclicked (don't have color class)
if (!this.classList.contains('color')) {
//add1:
var addTotal1 = Number(document.getElementsByName('total1').value);
var addSingle1 = Number(document.getElementById(this.id.toString() + 'add1').value);
addTotal1 -= addSingle1;
document.getElementById('totaladd1').value = addTotal1.toString();
//add2:
var addTotal2 = Number(document.getElementsByName('total2').value);
var addSingle2 = Number(document.getElementById(this.id.toString() + 'add2').value);
addTotal2 -= addSingle2;
document.getElementById('totaladd2').value = addTotal2.toString();
//add3:
var addTotal3 = Number(document.getElementsByName('total3').value);
var addSingle3 = Number(document.getElementById(this.id.toString() + 'add3').value);
addTotal3 -= addSingle3;
document.getElementById('totaladd3').value = addTotal3.toString();
}
})
});
<div class="row p-lg-5">
<div id="div1" class="select-class">
<p>Content</p>
<!--hidden values-->
<div class="d-none">
<input type="number" class="add1" id="div1add1" value="1" />
<input type="number" class="add2" id="div1add2" value="45" />
<input type="number" class="add3" id="div1add3" value="4" />
</div>
</div>
<div id="div2" class="select-class">
<p>Content</p>
<!--hidden values-->
<div class="d-none">
<input type="number" class="add1" id="div2add1" value="3" />
<input type="number" class="add2" id="div2add2" value="20" />
<input type="number" class="add3" id="div2add3" value="3" />
</div>
</div>
</div>
<!--hidden totals-->
<div class="d-none">
<input id="totaladd1" type="number" name="total1" value="0" />
<input id="totaladd2" type="number" name="total2" value="0" />
<input id="totaladd3" type="number" name="total3" value="0" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Set your add inputs as disabled by default
Add a data-total="" to every total input. Inside the data place the add-inputs-pairs selector i.e: ".add_1" etc...
Toggle class on click and perform a search for the non disabled add inputs, reducing their values to an accumulated number. Set that number as the iterating total input value
jQuery(function($) {
function calculateTot() {
$('[data-total]').each(function() {
const pair = $(this.dataset.total).not(':disabled').get();
$(this).val(pair.reduce((n, el) => (n += +el.value, n), 0))
});
}
$('.select-class').on('click', function() {
$(this).toggleClass('is-selected');
$(this).find('input').prop('disabled', !$(this).is('.is-selected'));
calculateTot();
}).find('input').prop('disabled', true); // Make inputs disabled by default
calculateTot(); // Calculate also on DOM ready
});
.select-class {cursor:pointer; padding:8px; border-radius:1em; border:1px solid #000;}
.is-selected {background:#0bf;}
.d-none {display:none;}
<div class="row p-lg-5">
<div id="div1" class="select-class">
Content 1 - Select me
<div class="d-none">
<input type="number" class="add_1" value="1" />
<input type="number" class="add_2" value="45" />
<input type="number" class="add_3" value="4" />
</div>
</div>
<div id="div2" class="select-class">
Content 2 - Select me
<div class="d-none">
<input type="number" class="add_1" value="3" />
<input type="number" class="add_2" value="20" />
<input type="number" class="add_3" value="3" />
</div>
</div>
</div>
<div> <!-- class="d-none" -->
<input data-total=".add_1" type="number" name="total1" />
<input data-total=".add_2" type="number" name="total2" />
<input data-total=".add_3" type="number" name="total3" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I am currently trying to create a tip calculator app using JS, HTML, and CSS. My issue is that the input value is submitted when the button is clicked, but once submitted, the value just flashes for less than a second, then it vanishes. I would like for the value to stay on the screen once submitted.
let dinTotal = document.querySelector('#cost');
let dinService = document.querySelector('#service');
let dinSize = document.querySelector('#size');
let calcBtn = document.querySelector('button');
let total = 0;
let amount = document.querySelector('#amount')
calcBtn.addEventListener('click', function() {
if(dinTotal.value >= 50 && dinService.value < 5 && dinSize.value < 5) {
total = (dinTotal.value * 0.10) + dinTotal.value ;
amount.textContent = total;
}
})
<form>
<h1>Tip & Dip✌️</h1>
<hr>
<!-- Bill Section -->
<div>
<label for='cost'>Dinning amount</label>
</div>
<input name='cost' id='cost' type='number' placeholder='$' required>
<!-- Service Section-->
<div class='top-space'>
<label for='service'>How was the service</label>
</div>
<input name='service' id='service' type='number' placeholder='rate 1-10' required>
<!-- Party Size-->
<div class='top-space'>
<label for='size'>Party Size</label>
</div>
<div>
<input name='size' id='size' type='number' required>
</div>
<div class='top-space'>
<button>LET'S CALCULATE...</button>
</div>
<hr>
<h2>Total: $<span id='amount'>0</span></h2>
</form>
The default behavior of a button is to submit the form. When a form submits, if you don't stop it, it will unload the current page and submit the data to its action URL. With no action attribute, a form submits to the current page, causing your reload.
Set the type attribute on your button to button to prevent it from being a submit button.
<button type="button">LET'S CALCULATE...</button>
use the preventDefualt() method of the event callback
calcBtn.addEventListener('click', function(event) {
event.preventDefault()
}
Full working snippet (though it only updates for size and value of less than 5 and checks greater than 50 I hope you know)
let dinTotal = document.querySelector('#cost');
let dinService = document.querySelector('#service');
let dinSize = document.querySelector('#size');
let calcBtn = document.querySelector('button');
let total = 0;
let amount = document.querySelector('#amount')
calcBtn.addEventListener('click', function(event) {
event.preventDefault()
if(dinTotal.value >= 50 && dinService.value < 5 && dinSize.value < 5)
{
total = (dinTotal.value * 0.10) + dinTotal.value ;
console.log(total)
amount.textContent = total;
}
})
<form>
<h1>Tip & Dip✌️</h1>
<hr>
<div>
<label for='cost'>Dinning amount</label>
</div>
<input name='cost' id='cost' type='number' placeholder='$' required>
<div class='top-space'>
<label for='service'>How was the service</label>
</div>
<input name='service' id='service' type='number' placeholder='rate 1-10' required>
<div class='top-space'>
<label for='size'>Party Size</label>
</div>
<div>
<input name='size' id='size' type='number' required>
</div>
<div class='top-space'>
<button>LET'S CALCULATE...</button>
</div>
<hr>
<h2>Total: $<span id='amount'>0</span></h2>
</form>
no matter what i try i cant get the function to run properly
ive tried checked that the inputs are numbers, and only the output is giving me NaN. ive tried putting parseInt around the inputs, but the inputs eem to be working correctly. its probably a small newb mistake, thanks for your time anyway!
const principle=parseInt(document.getElementsByClassName('principle').value);
const rate = parseInt(document.getElementsByClassName('.rate').value);
const payments = parseInt(document.getElementsByClassName('payments').value);
let interest;
function calculate() {
console.log(typeof(principle));
console.log(typeof(rate));
console.log(typeof(payments));
interest = (rate / payments) * principle;
console.log(interest);
};
<body>
<h1>interest calculator</h1>
<div class="container">
<div class="row">
<div class="col-4-md">
initial amount <input type="number" name="" value="" class="principle px-3">
</div>
<div class="col-4-md">
interest rate <input type="number" name="" value="" class="rate px-3">
</div>
<div class="col-4-md">
Number of payments <input type="number" name="" value="" class="payments px-3">
</div>
<button type="submit" name="button" onclick="calculate()">Submit</button>
</div>
</div>
i just want the output to be a number
Here is a working code after modifications/fixes:
<html>
<head>
<script>
let interest;
function calculate() {
const principle=parseInt((document.getElementsByClassName('principle')[0]).value);
const rate = parseInt((document.getElementsByClassName('rate')[0]).value);
const payments = parseInt((document.getElementsByClassName('payments')[0]).value);
console.log(typeof(principle));
console.log(principle);
console.log(typeof(rate));
console.log(rate);
console.log(typeof(payments));
console.log(payments);
interest = (rate / payments) * principle;
console.log(interest);
};
</script>
</head>
<body>
<h1>interest calculator</h1>
<div class="container">
<div class="row">
<div class="col-4-md">
initial amount <input type="number" name="" value="" class="principle px-3">
</div>
<div class="col-4-md">
interest rate <input type="number" name="" value="" class="rate px-3">
</div>
<div class="col-4-md">
Number of payments <input type="number" name="" value="" class="payments px-3">
</div>
<button type="submit" name="button" onclick="calculate()">Submit</button>
</div>
</div>
</body>
</html>
You have 2 mistakes in your JS.
1) getByClassName return an array of element, so you must select which element you want in your case, since you have only one element of each, you can easily do document.getElementsByClassName('rate')[0]
2) at the moment you load the page, you assign your values. but when you fill the document, and calculate, you don't check the value again. so they are still undefined.
if you fix everything you will get this JS
const principle$ = document.getElementsByClassName('principle')[0];
const rate$ = document.getElementsByClassName('rate')[0];
const payments$ = document.getElementsByClassName('payments')[0];
let interest;
function calculate() {
console.log(principle$, principle$.value)
const principle = parseInt(principle$.value);
const rate = parseInt(rate$.value);
const payments = parseInt(payments$.value);
interest = (rate / payments) * principle;
console.log(interest);
};
https://codepen.io/crocsx-the-styleful/pen/MWgOLgm
Becuase typeof NaN is also a number
console.log(typeof NaN)
When you JS code execute the variable are outside the function so the are calculated with as soon as your script load, during that time your inputs hold empty string
console.log(parseInt(''), typeof parseInt(''))
You need to move your variables inside the function so they will be evaluated when the submit button is pressed
function calculate() {
const principle = parseInt(document.getElementsByClassName('principle')[0].value);
const rate = parseInt(document.getElementsByClassName('rate')[0].value);
const payments = parseInt(document.getElementsByClassName('payments')[0].value);
let interest;
console.log(typeof(principle));
console.log(typeof(rate));
console.log(typeof(payments));
interest = (rate / payments) * principle;
console.log(interest);
};
<body>
<h1>interest calculator</h1>
<div class="container">
<div class="row">
<div class="col-4-md">
initial amount <input type="number" name="" value="" class="principle px-3">
</div>
<div class="col-4-md">
interest rate <input type="number" name="" value="" class="rate px-3">
</div>
<div class="col-4-md">
Number of payments <input type="number" name="" value="" class="payments px-3">
</div>
<button type="submit" name="button" onclick="calculate()">Submit</button>
</div>
</div>
Also you're using getElementsByClassName which returns a node list, you need to access particular node using index