why am i getting undefined error from input value? - javascript

so, when i console.log document.getElementById("deposit-amount").value I get real time numbers/data. But when I put it into variable and console.log the name (depositAmount), it shows undefined.
html
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn">Deposit</button>
</div>
js
const depositAmount = document.getElementById("deposit-amount").value;

Seems to work fine in this snippet. Is there any more code you can share to debug?
function log() {
console.log(document.getElementById('deposit-amount').value);
}
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn" onclick="log()">Deposit</button>
</div>

<div class="box-1 common-box">
<p>Deposit</p>
<h2>$ <span id="current-deposit">01</span></h2>
</div>
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn">Deposit</button>
</div>
const depositBtn = document.getElementById("deposit-btn");
depositBtn.addEventListener("click", function(){
const depositAmount = document.getElementById("deposit-amount").value;
const depositNumber = parseFloat(depositAmount);
const cuurentDeposit = document.getElementById("current-deposit").innerText;
const currentNumber = parseFloat(cuurentDeposit);
const total = depositNumber + currentNumber;
document.getElementById("current-deposit").innerText = total;
document.getElementById("deposit-amount").value = "";
})
This works. but still when I console.log the name (depositAmount), it shows undefined.Is this because DOM isn't ready? How to resolve this? -#nemo

Related

Vanilla Javascript - add amount of input to total value with different minimum values on inputs

I have three different inputs inside a modal that represents three different "stock" items. if a user adds a value in the input related to that specific item with a minimum of the value stipulated I want to add that input value to the total amount. but I'm stuck with looping over the buttons and calling the addAmount function to get the correct input.
I might be overcomplicating things as I'm quite new to this.
any guidance would be appreciated
const btns = document.querySelectorAll('.add-stock');
const inputs = document.querySelectorAll('[data-stock-amount]');
let totalAmount = document.querySelector('.total-amount');
totalValue = 5000;
const addAmount = (e) => {
inputs.forEach(input => {
let setAmount = input.value;
let inputData = input.dataset.stockAmount;
if (inputData === "stock25") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
if (inputData === "stock50") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
if (inputData === "stock100") {
totalValue = parseFloat(totalValue) + parseFloat(setAmount);
totalAmount.innerHTML = totalValue;
}
});
}
btns.forEach(btn => {
btn.addEventListener('click', (e) => {
let btnData = e.target.dataset.addStock;
if (btnData === inputData) {
addAmount(e);
}
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
Your code is significantly longer and more complicated than it needs to be. Here's a way to get you started:
const btns = document.querySelectorAll(".add-stock");
const totalAmount = document.querySelector(".total-amount");
/* Increment the total amount by the given amount. */
const addAmount = amount => {
// The '+' before the variable casts the value to a number.
totalAmount.innerHTML = +totalAmount.innerHTML + +amount;
}
btns.forEach(btn => {
btn.addEventListener("click", e => {
/* Cache the stock amount of the clicked button. */
let btnData = e.target.dataset.addStock;
/* Use the above value to find the related input. */
let input = document.querySelector("[data-stock-amount = '" + btnData + "']");
/* Parse the stock amount to find the default value. */
let defaultValue = +btnData.replace("stock", "");
/* If the current value exceeds or equals the default, add it. */
if (input.value >= defaultValue) addAmount(input.value);
/* Otherwise, print a warning on the console. */
else console.log(input.value + " is less than the default of " + defaultValue);
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card"><input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25"><label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card"><input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50"><label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card"><input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100"><label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
I believe this code meets your requirements, please see the code comments for details. This approach requires only 1 event listener to be added to a single parent element of the buttons we want to listener to click events for - this technique is called event delegation and is a cleaner approach than adding many event listeners:
const inputEls = document.querySelectorAll('[data-stock-amount]');
const totalAmountEl = document.querySelector('.total-amount');
// Get the initial values and store them as minimums
const minimumStockValues = Array.from(inputEls).reduce((map, stock) => {
map.set(stock.name, stock.value);
return map;
}, new Map());
// Add an event listener on the modal for button clicks
document.querySelector('.modal').addEventListener('click', event => {
if (event.target.tagName === 'BUTTON') {
// Get the input that corresponds to the button that was clicked
const inputEl = document.querySelector(`[data-stock-amount='${event.target.dataset.addStock}']`);
// Compare the value in the input with the allowable minimum amount and take some action
if (inputEl.value >= minimumStockValues.get(inputEl.name)) {
totalAmountEl.innerHTML = parseInt(totalAmountEl.textContent) + parseInt(inputEl.value);
} else {
console.error(`Minimum amount allowed for ${inputEl.name} is $${minimumStockValues.get(inputEl.name)}`);
}
}
});
<div class="total">$<span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>
You are overcomplicating the logic. Just grab the input value and default value and get the max of it and add it to totalAmount.
const btns = document.querySelectorAll(".add-stock");
const inputs = document.querySelectorAll("[data-stock-amount]");
let totalAmount = document.querySelector(".total-amount");
btns.forEach((btn) => {
btn.addEventListener("click", (e) => {
const minValue = e.target.dataset.addStock.match(/[\d]+/g)[0];
const inputValue = e.target.parentNode.querySelector("input").value;
let totalAmountData = +totalAmount.textContent;
totalAmount.textContent = totalAmountData + Math.max(minValue, inputValue);
});
});
<div class="total">$ <span class="total-amount">5000</span></div>
<div class="modal">
<div class="card">
<input type="number" name="stock1" id="stock1" value="25" data-stock-amount="stock25">
<label for="stock1">Stock1</label>
<button class="add-stock" data-add-stock="stock25">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock2" id="stock2" value="50" data-stock-amount="stock50">
<label for="stock2">Stock2</label>
<button class="add-stock" data-add-stock="stock50">Add Stock</button>
</div>
<div class="card">
<input type="number" name="stock3" id="stock3" value="100" data-stock-amount="stock100">
<label for="stock3">Stock3</label>
<button class="add-stock" data-add-stock="stock100">Add Stock</button>
</div>
</div>

How will i show my data output inside an input element using Jquery

Here is my Javascript code:
$('#sb_add_ctrl').click(function() {
var value = $('#sel_control_num').val();
for (var i = 1; i <= 5; i++) {
value = value.replace(/(\d+)$/, function(match, n) {
const nextValue = ++match;
return ('0' + nextValue).slice(1);
});
$('#parent')[0].innerHTML += '<br>' + value;
}
})
Here is my HTML code:
<div><label> Control Number </label>
<input name="get_control_num" style="text-transform:uppercase"
class="form-control" id="sel_control_num" readonly>
</div>
<div class="form-group">
<label> Quantity </label>
<input class="form-control" name="quantity" type="number"
/>
<br>
<button type="button" id="sb_add_ctrl" class="btn btn-primary"> Add
Control Number </button>
</div>
<div class="form-group" id="parent"></div>
What I want to do is get the existing class of the input and show the data that is in innerHTML into an input element .I can't think of a proper solution cause I am still a beginner in javascript/jquery, I tried the other methods in jquery but still it doesn't work thanks for the help

Is there a way to edit a javascript function to live update in a html form output?

I've written a working absence calculator using a HTML form and a javascript function. Unfortunately I need this to update to the output in real time and I cannot figure out how to do it without firing the function multiple times.
HTML
<form id="absence-form">
<div class="input">
<div id="title">Absence Calculator</div>
<div id="firstCell">
<div id="instruct">
Enter number of employees:
</div>
<input id="employees" type="text" name="employees">
<div id="secondCell">
<div id="instruct">
Enter average salary:
</div>
</div>
<input id="salary" type="text" name="salary">
<div id="thirdCell">
<div id="instruct">
Enter absence %:
</div>
</div>
<input id="absence" type="text" name="absence">
</div>
<div id="instruct">
<div id="output">Total salary (£):
<div id="totalSalary">
</div></div>
<div id="output">Monthly absence cost (£):
<span id="monthlyAbsence">
</span></div>
<div id="output">Annual absence cost (£):
<span id="absenceCost">
</span></div>
</div>
</div>
</form>
Javascript Function
function multiply() {
var employees = document.getElementById('employees').value;
var salary = document.getElementById('salary').value;
var totalSalary = parseInt(employees) * parseInt(salary);
var result1 = document.getElementById('totalSalary');
result1.innerHTML += totalSalary;
var absence = document.getElementById('absence').value;
var absenceCost = parseInt(totalSalary) / 100 * parseInt(absence);
var result2 = document.getElementById('absenceCost');
result2.innerHTML += absenceCost;
var monthlyAbsence = parseInt(absenceCost) / 12;
var result3 = document.getElementById('monthlyAbsence');
result3.innerHTML += monthlyAbsence;
}
});
Any pointers would be greatly appreciated.
You'll need to bind your function to the change event for the input elements.
This can be done a couple of ways:
Obtrusively (not recommended) with the element's onChange attribute (JSFiddle)
Non-obtrusively (preferred) with .on('change', function() {} }) (JSFiddle)
I'm assuming from the tag that you're using jQuery but you can achieve the same thing with vanilla JS using .addEventListener('change', callback, false) (JSFiddle)

Output wont show (javascript)

I have 1 input. And it has to print out 2 outputs 1 with -1 to the output and the other with -2. But the output doesn't show anything. can someone tell me what I'm doing wrong here.
Code:
// Meters en Centimeters value
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; ++i) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = total - 2;
document.getElementById("schermentotaal2").value = total - 1;
}
HTML Input:
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="">
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
HTML Output:
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value=""></input>
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value=""></input>
</div>
Thanks in advance :D
You're not calling your updateTotal anywhere. I suggest you run this function on the oninput event on your input field. This will make it so that whenever you enter a number it will run the function updateTotal.
You also have some additional errors, such as you are trying to get the element with the id total but don't have an element with this id in your HTML.
document.getElementById("total").value
I've changed this to be schermentotaal2 which is a valid id in your HTML:
document.getElementById("schermentotaal2").value
See working example below:
function updateTotal() {
const list = document.getElementsByClassName("AutosubmitCalculator");
const values = [];
for (let i = 0; i < list.length; i++) {
values.push(parseFloat(list[i].value));
}
let total = values.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});
document.getElementById("schermentotaal").value = (total - 2) || '';
document.getElementById("schermentotaal2").value = (total - 1) || '';
}
<div class="InputField InputMeters">
<input type="tel" name="iFenceMeters" id="FenceMeters" class="AutosubmitCalculator" data-minimum-length="1" tabindex="1" placeholder="00" maxlength="3" value="" oninput="updateTotal()" />
<div class="FormExclamation Tipped Hidden" id="FormCalculatorExclamationFence">0</div>
</div>
<div class="SummaryRow">
<strong>Schermen</strong>
<input name="schermentotaal" type="text" id="schermentotaal" value="" />
</div>
<div class="SummaryRow">
<strong>Palen en onderplaten</strong>
<input name="schermentotaal2" type="text" id="schermentotaal2" value="" />
</div>
Also, if you only have one input you may want to reconsider using a class to get the input value for this as you don't require a loop to get the value from one input field.

Display JavaScript Math Result

I am having trouble displaying a math function, there is nothing stated wrong in the console, so I do not know where I am going wrong. the output does not display the correct answer here...
Desired outcome: enter number in each input, and javascript multiplies those two input values then displays the result when you click the button.
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
var myOutput = money * years;
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
output.innerHTML = myOutput;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>
I would structure it like this:
const btn = document.getElementById('btn');
const money = document.getElementById('money');
const years = document.getElementById('years');
const output = document.getElementById('output');
btn.addEventListener('click', () => {
output.innerHTML = Number(money.value) * Number(years.value);
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>
As others have said, you need to move the logic inside the click handler. (In your code as it's structured, you get the two values once, at the load of the script and never update them.)
I have also broken out the searching of the DOM nodes from the calculation; it's probably a good practice for anytime such changes can happen more than once.
Finally, I converted the String values you'll get from the form elements into numbers before doing any work with them. This is generally necessary, although because of some Javascript magic, you don't actually have to do it here. (Try changing from multiplication to addition to see the dangers of forgetting this.)
When you init your application, your input fields don't have any value filled yet.
var money = document.getElementById('money');
var years = document.getElementById('years');
var output = document.getElementById('output');
const btn = document.getElementById('btn');
function calc(val1, val2) {
return Number(val1.value) * Number(val2.value);
}
btn.addEventListener('click', (e) => {
output.innerHTML = calc(money, years);
});
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>
You need to set the innerHTML of the element. You want to get the user input values after the click of the button. Therefore, you move your variables inside the callback function
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
output.innerHTML = money * years;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>
Try this set inner html of div and have everything but the btn element happen on click:
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
var myOutput = money * years;
output.innerHTML = myOutput;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>

Categories