I was making a simple calculator with two input boxes for each number, and four buttons for each operation underneath. After pressing one of the buttons (Ex:Add) They would perform the operation. However, inside each function I had to keep writing these two lines:
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
Is there a way I could write these before I make each individual function? Could someone with more skill possibly show me what I could do?
function add() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 + Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function sub() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 - Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function mul() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 * Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function div() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 / Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Is there a way I could write these before I make each individual function?
You can get the elements just once:
const input1 = document.getElementById("Value1");
Then when you need its value:
const value1 = input1.valueAsNumber;
In general, you can usually write a function to avoid duplicated logic. Probably not appropriate in this case, but for example:
function getValueAsNumber(id) {
return document.getElementById(id).valueAsNumber;
}
then
const value1 = getValueAsNumber("Value1");
A couple of side notes:
In JavaScript and related languages, the overwhelming convention is to use an initial lower case letter for variables that don't refer to constructor functions. So value1 rather than Value1, value1Element rather than Value1Element, etc.
var is no longer best practice in JavaScript. In new code, prefer let or const because of their more useful scoping.
When putting just plain text in an element, you're better off using textContent rather than innerHTML, because the browser doesn't try to parse the text you give it as HTML.
onxyz-attribute-style event handlers are not best practice, not least because the functions they call have to be globals, and the global namespace is crowded. Consider using modern event handling (addEventListener and the like).
Just for an example, here's your code with some of the above applied, but without going overboard:
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
gid("add").addEventListener("click", () => {
const total = input1.valueAsNumber + input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("sub").addEventListener("click", () => {
const total = input1.valueAsNumber - input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("mul").addEventListener("click", () => {
const total = input1.valueAsNumber * input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("div").addEventListener("click", () => {
const total = input1.valueAsNumber / input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Or we could abstract away everything but the operation itself (just for fun):
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
const clickHandler = (id, operation) => {
// ^^^^^^^^^
gid(id).addEventListener("click", () => {
const total = operation(input1.valueAsNumber, input2.valueAsNumber);
// ^^^^^^^^^
demo.textContent = "Total: " + total;
});
};
clickHandler("add", (a, b) => a + b);
// ^^^^^^^^^^^^^^^
clickHandler("sub", (a, b) => a - b);
clickHandler("mul", (a, b) => a * b);
clickHandler("div", (a, b) => a / b);
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You could even go further than that, but it starts getting hard to follow. :-)
You can make a function to get the value of an element by ID, and re-use it, also you can create 1 function that will show the total as well.
function showTotal(total) {
document.getElementById('demo').innerHTML = "Total: " + total;
}
function getValue(id) {
return document.getElementById(id).valueAsNumber;
}
function add() {
showTotal(getValue("Value1") + getValue("Value2"));
}
function sub() {
showTotal(getValue("Value1") - getValue("Value2"));
}
function mul() {
showTotal(getValue("Value1") * getValue("Value2"));
}
function div() {
showTotal(getValue("Value1") / getValue("Value2"));
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>
Some suggestions:
Let's separate the calculating from the formatted displaying. We'll have one function to calculate (+, -, /, *) and a different function to handle innerHTML-setting.
Since the calculations are all in one function, that removes the redundancy of multiple document.getElementById calls throughout your code.
We can use a switch() statement to determine the operation to apply, although a standard if()/else() also would work.
Working demo...
function operate(e) {
var Total = getOperationTotal(e);
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function getOperationTotal(e) {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var total;
switch(e.target.id) {
case 'add-button':
total = Value1 + Value2;
break;
case 'subtract-button':
total = Value1 - Value2;
break;
case 'multiply-button':
total = Value1 * Value2;
break;
case 'divide-button':
total = Value1 / Value2;
break;
}
return total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button id="add-button" type="button" onclick="operate(event)">Add</button>
<button id="subtract-button" type="button" onclick="operate(event)">Subtract</button>
<button id="multiply-button" type="button" onclick="operate(event)">Multiply</button>
<button id="divide-button" type="button" onclick="operate(event)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You can define global variables and additionally add onchange functions for the input, so as soon as you change the number the value changes in JS too.
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
function updateNr(id){
(id === 1) ? Value1 = document.getElementById('Value1').valueAsNumber : Value2 = document.getElementById('Value2').valueAsNumber;
}
function add() {
var Total = Value1 + Value2;
postAnswer(Total);
}
function sub() {
var Total = Value1 - Value2;
postAnswer(Total);
}
function mul() {
var Total = Value1 * Value2;
postAnswer(Total);
}
function div() {
var Total = Value1 / Value2;
postAnswer(Total);
}
function postAnswer(total){
document.getElementById('demo').innerHTML = "Total: " + total;
}
First Number: <input onchange="updateNr(1)" type="number" id="Value1"><br><br>
Second Number: <input onchange="updateNr(2)" type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="action(this)">Add</button>
<button type="button" onclick="action(this)">Subtract</button>
<button type="button" onclick="action(this)">Multiply</button>
<button type="button" onclick="action(this)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<script>
action = (e) => {
const Value1 = document.getElementById('Value1').valueAsNumber;
const Value2 = document.getElementById('Value2').valueAsNumber;
let Total = null;
switch(e.textContent) {
case 'Add':
Total = Value1 + Value2;
break;
case 'Subtract':
Total = Value1 - Value2;
break;
case 'Multiply':
Total = Value1 * Value2;
break;
case 'Divide':
Total = Value1 / Value2;
break;
}
document.getElementById('demo').innerHTML = `Total: ${Total}`;
}
</script>
</body>
We dont need to write each function for each calculation, Try to reuse the code insted of re-writing it, Since you are trying to execute the same logic but only the arithmetic operators are changed in each function you defined, we can write a single function and change the operators depending on the calculations we intend to perform. Below code uses function calculate(operation) which takes operation as a parameter and gives us the result depending on the argument passed.
Always try to use let insted of var as let has block scope but var doesn't
Also for better code readability and consistency follow naming conventions to name your variables
function calculate(operation){
let total;
let value1 = document.getElementById('Value1').valueAsNumber;
let value2 = document.getElementById('Value2').valueAsNumber;
if(operation == 'add') total = value1 + value2;
else if(operation == 'sub') total = value1 - value2;
else if(operation == 'multiply') total = value1 * value2;
else if(operation == 'devide') total = value1 / value2;
document.getElementById('demo').innerHTML = "Total: " + total;
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="calculate('add')">Add</button>
<button type="button" onclick="calculate('sub')">Subtract</button>
<button type="button" onclick="calculate('multiply')">Multiply</button>
<button type="button" onclick="calculate('devide')">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>
Related
I would like to ask a bit of help. I was creating a simple calculator. The problem is my calculator displays the same results everytime. The addition would display nothing, the subtraction and multiplication would display 0, and the division and modulo would display NaN. Here is my code:
let a = document.getElementById("num1").innerHTML;
let b = document.getElementById("num2").innerHTML;
function addFunction() {
let add = a + b;
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = a - b;
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = a * b;
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = a / b;
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = a % b;
document.getElementById("result").innerHTML = modulo;
}
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1">
<input id="num2">
<br>
<br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
You should get values of input not innerHTML like this
var a = document.getElementById("num1").value
var b = document.getElementById("num2").value
And then convert it to number like this
a = parseFloat(a)
b = parseFloat(b)
You need to do this:
let a = parseFloat(document.getElementById("num1").value);
let b = parseFloat(document.getElementById("num2").value);
You need .value to get the text of the input field, this will return a string so you also need to use the Unary Plus (+) to convert it to a number:
+document.getElementById("num1").value;
+document.getElementById("num2").value;
Since the content of both input boxes change throughout the program, you would need to run the lines above mulitple times to get the updated content. You can do this with functions:
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
To prevent the user from entering characters that aren't numbers you can also set the input type:
<input id="num1" type="number">
<input id="num2" type="number">
Full code:
<html>
<body>
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1" type="number">
<input id="num2" type="number">
</br>
</br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
<script>
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
function addFunction() {
let add = getA() + getB();
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = getA() - getB();
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = getA() * getB();
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = getA() / getB();
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = getA() % getB();
document.getElementById("result").innerHTML = modulo;
}
</script>
</body>
</html>
I'm new to JavaScript. I did a simple calculator that has 2 inputs values with 4 buttons of operators. How can I fix this JavaScript so that it can count the numbers based on different operators and display the correct output? How to write it using if else condition or switch cases?
Now I have pressed every button it only shows the output with sum only.
function count() {
var n1 = parseFloat(document.getElementById("num1").value);
var n2 = parseFloat(document.getElementById("num2").value);
var optr = document.getElementById("operator").value;
let result;
if (optr == '+') {
result = n1 + n2;
} else if (optr == '-') {
result = n1 - n2;
} else if (optr == '*') {
result = n1 * n2;
} else {
result = n1 / n2;
}
document.getElementById("output").innerHTML = "Total is: " + result;
}
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" onclick="count()" id="operator">
<input type="button" value="-" onclick="count()" id="operator">
<input type="button" value="*" onclick="count()" id="operator">
<input type="button" value="/" onclick="count()" id="operator">
<p id="output"></p>
There are many ways to achieve what you want. Here is one that I have prepared by modifying/simplifying your original code:
const in1 = document.getElementById("num1"),
in2 = document.getElementById("num2");
document.addEventListener("click", function(ev) {
if (ev.target.classList.contains("operator")) {
let optr = ev.target.value,
n1 = +in1.value,
n2 = +in2.value,
result;
if (optr == '+') result = n1 + n2;
else if (optr == '-') result = n1 - n2;
else if (optr == '*') result = n1 * n2;
else result = n1 / n2;
document.getElementById("output").innerHTML = "Total is: " + result;
}
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">
<p id="output"></p>
A few remarks:
id attributes must always be unique on a page. I replaced the ids in your buttons by class attributes.
the values of your input elements must be evaluated at the time the operator button is clicked.
the conversion from text to numerical values is done implicitly by applying the unary + operator in front of in1.value and in2.value.
instead of assigning the handler function through the html-onclick attribute I used a delegated event attachment: the click event is attached to the whole document but will only cause an action if the actual clicked element (ev.target) has the word "operator" in its class list.
Switch case or If/else. Both is right. But I prefer the switch case version, because it is cleaner. Following #CarstenMassmann's answer, here is the switch case path:
const in1 = document.getElementById("num1");
const in2 = document.getElementById("num2");
document.addEventListener("click", function(e) {
if (e.target.classList.contains("operator")) {
const optr = e.target.value
const n1 =+ in1.value;
const n2 =+ in2.value;
let result = 'i dont know';
switch (optr) {
case '+':
result = n1 + n2
break;
case '-':
result = n1 - n2
break;
case '*':
result = n1 * n2;
break;
case '/':
result = n1 / n2;
}
document.getElementById("output").innerHTML = "= " + result;
}
})
Number 1:<input type="number" id="num1"><br><br> Number 2:<input type="number" id="num2"><br><br>
<input type="button" value="+" class="operator">
<input type="button" value="-" class="operator">
<input type="button" value="*" class="operator">
<input type="button" value="/" class="operator">
<p id="output"></p>
(ETA: I'm working on this for a class and the teacher wants everything to be "oninput"...yes, it's annoying :p )
I'm working on a form where each function miltiplies a number and gives me a "subtotal" on input. I'd like to take the two "subtotal" answers from the two functions and add them togething into a "total" amount. I feel like this should be simple but nothing I've tried works.
Here's what I've got in the javascript that works to give me the two subtotals:
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
document.getElementById('subTotalOne').innerHTML = '$ ' + qty1 * 19.99;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
document.getElementById('subTotalTwo').innerHTML = '$ ' + qty2 * 37.99;
}
Here's the important parts of the html:
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()"/><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()"/><br>
</div>
<div class="price">
<label for="price">Price</label>
<p>$19.99</p>
<p>$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
I'm trying to add the subTotalOne and subTotalTwo and have them output at orderTotal, essentially. :)
Thanks!
//Global variables (concidering ID is unique)
let subTotalOne, subTotalTwo, qty1, qty2, orderTotal;
const setup = () => {
subTotalOne = document.getElementById('subTotalOne');
subTotalTwo = document.getElementById('subTotalTwo');
qty1 = document.getElementById('qty1');
qty2 = document.getElementById('qty2');
orderTotal = document.getElementById('orderTotal');
myCalculator();
myCalculatorTwo();
};
const updateTotal = (target, value) => {
if(target == null || value == null || Number.isNaN(value)) return;
target.textContent = `$ ${value.toFixed(2)}`;
target.setAttribute('data-value', value.toFixed(2));
}
const getTotal = () => {
if(subTotalOne == null || subTotalTwo == null) return 0;
const [value1, value2] = [
Number.parseFloat((subTotalOne.dataset?.value ?? 0), 10),
Number.parseFloat((subTotalTwo.dataset?.value ?? 0), 10)
];
if(Number.isNaN(value1) || Number.isNaN(value2)) return;
else return value1 + value2;
};
const updateOrderTotal = () => updateTotal(orderTotal, getTotal());
const myCalculator = () => {
const value = Number.parseFloat(qty1.value || 0, 10) * 19.99;
updateTotal(subTotalOne, value);
updateOrderTotal();
}
const myCalculatorTwo = () => {
const value = Number.parseFloat(qty2.value || 0, 10) * 37.99;
updateTotal(subTotalTwo, value);
updateOrderTotal();
}
window.addEventListener('load', setup);
<div class="qty">
<label for="qty">Qty</label><br>
<input type="number" id="qty1" placeholder="0" oninput="myCalculator()" min="0"><br>
<input type="number" id="qty2" placeholder="0" oninput="myCalculatorTwo()" min="0"><br>
</div>
<div class="price">
<label for="price">Price</label>
<p data-value="19.99">$19.99</p>
<p data-value="37.99">$37.99</p>
</div>
<div class="subtotal">
<label for="subTotal">Total</label><br>
<span class="subTotalOne" id="subTotalOne">$</span><br>
<span class="subTotalTwo" id="subTotalTwo">$</span><br>
</div>
<div class="total">
<label for="total">Order Total</label><br>
<span class="orderTotal" id="orderTotal" oninput="orderTotal()">$</span><br>
</div>
Here's how you do it:
function orderTotal() {
const qty1 = document.getElementById('qty1').value;
const qty2 = document.getElementById('qty2').value;
const total = parseInt(qty1) + parseInt(qty2);
document.getElementById('orderTotal').innerHTML = '$ ' + total;
}
Remove the oninput="orderTotal()" in your span element and trigger the above function using a button click e.g. <button onClick="orderTotal()">Calculate Total</button> or maybe when either of your two inputs' value changes. Also consider using const and let instead of var.
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/
Instead of querying the DOM in Ray's answer--as DOM queries should generally be avoided since they are slow W3 Wiki, you could also consider using a shared variable between the two functions.
Also, consider using something else in place of innerHTML, mostly because of efficiency why-is-element-innerhtml-bad-code.
var total1;
var total2;
function myCalculator() {
var qty1 = document.getElementById('qty1').value;
total1 = qty1 * 19.99
document.getElementById('subTotalOne').textContent = '$ ' + total1;
}
function myCalculatorTwo() {
var qty2 = document.getElementById('qty2').value;
total2 = qty2 * 37.99;
document.getElementById('subTotalTwo').textContent = '$ ' + total2;
}
function orderTotal() {
document.getElementById('orderTotal').innerHTML = '$ ' + (total1 + total2);
//parentheses because '$' isn't a number so the numbers total1 and total2 will be treated like strings and joined together
}
//I'm trying to get a result in meters out of an input in feet.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
//For any number I type I get 0 as answer.
var feetInput = document.getElementById("feet-input").value;
var result = document.getElementById("result");
var total;
function calculate(){
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
For any number I type get 0 as answer.
Because your var feetInput = document.getElementById("feet-input").value; is only executed once you need to fetch always latest value on function call as below
//var feetInput = document.getElementById("feet-input").value;//only executed once
var result = document.getElementById("result");
var total;
function calculate(){
var feetInput = document.getElementById("feet-input").value;
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
The only issue that you have is that the value from feet-input is ONLY read when the page is loaded.
You'll need to get the value of feet-input before you do the calculation.
Just add var feetInput = document.getElementById("feet-input").value; to the line immediately after function calculate(){
Codepen: https://codepen.io/DeathCamel57/pen/xPPGrp?editors=0010
Hello I am trying to rewrite a function that will increment / decrement more than 1 stepper in javascript. Here is what I tried so far
here is a codepen link http://codepen.io/Ongomobile/pen/XdyBgv/
Here is 1 of the steppers
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal("one",-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal("one",1)">+1</button>
</div>
// This is current one
function modify_qty(val) {
var qty = document.querySelector("#qty1").value;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.querySelector("#qty1").value = new_qty;
return new_qty;
}
This is what I tried
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(qty,10) + val;
if (new_qty < 0) {
new_qty = 0;
}
[name].value = new_qty;
return new_qty;
}
A few issues:
What's the purpose of this line parseInt(qty,10) + val;? parseInt is intended to convert a string into its equivalent digit. Not much point in calling it on a base10 number.
Not sure what the point of the name argument to stepperVal is. Isn't the amount to be stepped already implied by the value argument?
You can pass a reference to the object triggering the onclick event by passing this to your function declared within the onclick.
new_qty always evaluates to val
stepperVal(arg,-1) is actually the same as stepperVal(arg,0). Why not just call it that way?
Updated code
replace "one" with this in :
<div class="qtyDiv">
<label class="qtyLabel" for="qty1 " name"one"><abbr title="Quantity">Qty</abbr></label>
<input class="qtyInput" id="qty1" value="0" name"one" />
<!-- <button class=" tallyBtn" id="down" onclick="modify_qty(-1)">-1</button>
<button class="tallyBtn"id="up" onclick="modify_qty(1)">+1</button> -->
<button class=" tallyBtn" id="down" onclick="stepperVal(this,-1)">-1</button>
<button class="tallyBtn"id="up" onclick="stepperVal(this,1)">+1</button>
</div>
Simplified JS:
function stepperVal(event, val){
clicked_link = event.target
return clicked_link.value = Math.max(0, val); # Return the greater of 0 and `val`
}
Use following it must work:
function stepperVal(name,val){
var qty = 0;
var new_qty = parseInt(document.getElementsByName(name),10) + val;
if (new_qty < 0) {
new_qty = 0;
}
document.getElementsByName(name).value = new_qty;
return new_qty;
}