Change color as text entered in TextBox

0

Hello! I need a code that changes the background of some TextBox as soon as the page is loaded according to what was "caught" from the database, my idea would be: textBox has 2 possible values="SENT" and " NOT SENT ", the code changes the background to Green (SENT) or red (NOT SENT). I do not understand much of Javascript but I tried this and there was no success:

    <script type="text/javascript">

        function ChangeColor() {
        var cor = document.getElementById("cxtexto");
    if (cor == "ENVIADO")
        obj.style.backgroundColor = "#FF4D00";
    else
        obj.style.backgroundColor = "#0a719c";
}
    </script>

In a very brief way my PHP / html page is as follows:

<html>
<body onload="ChangeColor()">
<head>
 **Aqui vem o Script citado acima**
</head>
<td>JANEIRO<input type='text' value='ENVIADO' id='cxtexto'></td>
<td>FEVEREIRO<input type='text' value='NAO ENVIADO' id='cxtexto'></td>
</body>
</html> 

The VALUES above it pulls from the database (with PHP) but assuming they were described there, what would it be like? I did not find it but if there were any similar or similar questions, could you give me the link?

    
asked by anonymous 19.12.2017 / 18:48

2 answers

0

First thing is that you should not use the same id in more than one element. If you can, change id="cxtexto" to class="cxtexto" or add class equal to fields.

Then you can change the colors with document.querySelectorAll , traversing all input text and checking value :

(function ChangeColor() {
   var cor = document.querySelectorAll('input.cxtexto');
   
   for(var x=0; x<cor.length; x++){
      cor[x].style.backgroundColor = cor[x].value == "ENVIADO" ? "#090" : "#F30";
   }
}())
<td>JANEIRO<input type='text' value='ENVIADO' class='cxtexto'></td>
<td>FEVEREIRO<input type='text' value='NAO ENVIADO' class='cxtexto'></td>
    
19.12.2017 / 19:00
0

As already mentioned, you should not use elements with the same id in a document. But for my answer this does not matter.

  

Já que está carregando a pagina de acordo com o que foi "pego" do banco de dados , I would let PHP take care of giving colors to inputs according to the possible values returned, that is, "ENVIADO" e "NAO ENVIADO" .

Assuming that the table has the columns mes and estado with MySQLi would look like this:

$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "NOME_DB");

$sql=("SELECT * FROM tabela");
$result = mysqli_query($mysqli,$sql);

while($fetch= mysqli_fetch_assoc($result)) {
    $corFundo = $fetch['estado'] == "ENVIADO" ? "#090" : "#F30";
    echo  "<td>".$fetch['mes']."<input type='text' value='".$fetch['estado']."' id='cxtexto' style='background-color: ".$corFundo."'></td>";
}
    
20.12.2017 / 01:28