Input with less than three characters triggers function

Asked

Viewed 53 times

0

I’m performing a fixation exercise that asks for the following:

inserir a descrição da imagem aqui

The count is not working, it is picking up as if the number is greater than 3, for example number 12, and not if it has MORE than 3 characters.

Code:

function modificarAmarelo(){
      document.getElementById('mudar').style.backgroundColor = '#ffff00';
    }
    
    function perderFoco(){
      document.getElementById('mudar').style.backgroundColor = '';
      var caracteres = document.getElementById('mudar').value
      
      if (caracteres < 3){
        document.getElementById('mudar').style.backgroundColor = '#ff0000'
      } else{ 
        document.getElementById('mudar').style.backgroundColor = '#00ff00'
    }
    }
    <input id="mudar" type="text" onfocus="modificarAmarelo()" onblur="perderFoco()">

2 answers

1

To get the characters, you need to add the .length at the end of .value, which will return the number of characters in your input, thus:

var caracteres = document.getElementById('mudar').value.length;

This way it will return an integer number, representing the character count and its logic will work.

1


Your lost functionFoco missing to take the size of the string to carry out your if

function perderFoco(){
  document.getElementById('mudar').style.backgroundColor = '';
  var caracteres = document.getElementById('mudar').value

  if (caracteres.length < 3){
    document.getElementById('mudar').style.backgroundColor = '#ff0000'
  } else{ 
    document.getElementById('mudar').style.backgroundColor = '#00ff00'
}
}

Syntax in Javascript: str.length

Browser other questions tagged

You are not signed in. Login or sign up in order to post.