Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Restrict table data value to 4 digits

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 class="calculator">
    <tr>
        <td colspan="4"><input class="display-box" type="text" id="result" disabled /></td>
    </tr>
    <tr>
        <td><input class="button" type="button" value="1" onclick="display('1')" /> </td>
        <td><input class="button" type="button" value="2" onclick="display('2')" /> </td>
        <td><input class="button" type="button" value="3" onclick="display('3')" /> </td>
        <td><input class="button" 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
    result=result.split(/[+-/*]+/).pop();
    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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

enter image description hereHere, I use temp variable which store value of digit entered after a operator. initially the "value" give a digit in string type so, i convert it in number type and append this number in temp variable. when user click on the operator then temp value become 0, then this process continue until temp>9999 is satisfy and then an error msg is shown to user.

    temp = 0;
    function display(value) {
        var k = parseInt(value);
        console.log(k);
        temp = temp*10 + k; 
    document.getElementById("result").value += value;
    var ops = ["+", "-", "%", "*", "/"];
    
    result=document.getElementById("result").value
    if(ops.includes(value)){
        temp=0
        console.log("Ops found!")
        flag = true;
    }
    console.log(temp)
    console.log(result)
    if(temp>9999){
        document.getElementById("result").value = "Error"
        
        alert("Error: Entered more than 4 digits")
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

I would suggest splitting the result into operands, then checking the length of each operand. Example code below:

validResult = "1234+5678"
invalidResult = "12345+123"

function testResult(result) {
  console.log(`Testing "${result}"`);  
  
  // Get operands (i.e. find all numeric substrings)
  const operands = result.match(/[0-9]+/g);
  
  console.log(`Operands are ${operands.join(", ")}`); 
  
  // Measure length of operands
  for(const operand of operands) {
    if(operand.length > 4) {
      // Return false if any of the operands are > 4 digits
      console.log(`"${result}" is not valid`);
      return false;
    }
  }
  
  console.log(`"${result}" is valid`);
  return true;
}

// Prints true
console.log(testResult(validResult));

// Prints false
console.log(testResult(invalidResult));

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda