I am trying to build a simple calculator using HTML, CSS and Vanilla Javascript. Where I want to make sure that the input field (display screen) does not have more than 4 digits in the first operand and similarly for the next operands to follow.
Story so far
index.html
<table >
<tr>
<td colspan="4"><input type="text" id="result" disabled /></td>
</tr>
<tr>
<td><input type="button" value="1" onclick="display('1')" /> </td>
<td><input type="button" value="2" onclick="display('2')" /> </td>
<td><input type="button" value="3" onclick="display('3')" /> </td>
<td><input type="button" value="*" onclick="display('*')" /></td>
</tr>
...
</table>
script.js
function display(value) {
document.getElementById("result").value = value;
var ops = [" ", "-", "%", "*", "/"];
result=document.getElementById("result").value
console.log(result)
if(ops.includes(value)){
result=0 // Resetting result to 0
console.log("Ops found!")
}
result=document.getElementById("result").value // Result however takes current 5 digits
result=result.replace(/[^0-9]/g, '');
console.log(result)
if(result>9999){
document.getElementById("result").value = "Error"
alert("Error: Entered more than 4 digits")
}
}
This works for 1st set of operand, and then var result
takes 4 digits next operand(of length 1) i.e. next entered number which makes its length 5 and alert pops up. Ideally, result should be set to null on encountering any operator and then take the length of the next operand and so on.
CodePudding user response:
can you please attach screenshot of webpage with 5 or 4 digit number. code is looking good.
CodePudding user response:
Have you tried using the Number()
function? It is exactly what it says it is, it takes a string and converts it to a number. Then you can check if it is larger than 9,999.