-5

<input type="text" id="display" disabled>

javascript:

var display = document.getElementById('display');
var buttons = document.querySelectorAll('.key')
var equals = document.querySelector('equals')

function numDisplay(num){
display.value += num;
if(num === 'c'){
    display.value = '';
}

}

function ans(){
var x = display.value
x = eval(x);
display.value = x;
}

function root(){
var r = display.value
r = Math.sqrt(r);
display.value = r;
}


function remove(){
var displayVal = display.value;
displayVal= displayVal.slice(0, -1);
display.value = displayVal;
}

`

I have built a js calculator, and the only thing left to do is limit the number of digits displayed on the display to 10. What function, or attribute can i use to do that?

I have already tried the maxlength attribute. That doesn't work. It seems that the attribute is not being triggered at all.

I just want the text input field to display 10 characters instead of a never ending string of numbers.

  • Please share your Javascript/jQuery code. Thanks – Hassan Siddiqui Mar 29 '19 at 07:16
  • 3
    Possible duplicate of [Limit number of characters allowed in form input text field](https://stackoverflow.com/questions/8545376/limit-number-of-characters-allowed-in-form-input-text-field) – Abhishek Pandey Mar 29 '19 at 07:18
  • Ok, i got it to work by changing the input type to number, and using the max attribute. Works, but now if i press the clear key to clear the entry, the input tries to match the value type of the button and hence, i get a console warning. – Mashuk Shams Mar 29 '19 at 07:51

1 Answers1

1

maxlength only limits the length of user input in an element. If you set the contents of an element from Javascript, the browser assumes you know what you're doing and lets you ignore the limit.

If you want to round a floating-point number to a specific number of digits, use Number.toPrecision():

var a = 22/7;
console.log(a);
console.log(a.toPrecision(5));