Javascript + CSS: Doubt over Value or textContent

2

I made a condition that is not respecting the contents of text . Home Here is the code:

function teste() {
  var elements = document.getElementsByClassName("testetxt");
  if (elements.value =! null) {                  
    elements.style.border = 'solid 1px #00FF00;';
    alert("Ok");
  } else if (elements.value == null){
    elements.style.border = 'solid 1px #FF0000;';
    alert("Preencha o campo Código");
  }
}
<html>
  <body>
    <input class="testetxt" type="text"/>
    <button onclick="teste();" style="height:20px; width:20px;"> </button>
  </body>
</html
    
asked by anonymous 18.05.2018 / 20:58

2 answers

1

There are several issues in your code beyond those that @Marcos Brinner cited.

One of them is the value of style, which can not have a semicolon:

                                       errado!
                                          ↓
elements.style.border = 'solid 1px #00FF00;';

The ; within the quotation marks invalidates the value of style and will not make any effect.

Another problem is how to select elements by class:

var elements = document.getElementsByClassName("testetxt");

This returns a collection of nodes with class .testetxt and not element 1 itself. In this case, if you want to select the first element with this class, you would have to add the index [0] to the variable elements :

elements[0]

Another thing is that you can omit != null , leaving only if (elements[0].value) { .

See the corrected code:

function teste() {
  var elements = document.getElementsByClassName("testetxt");
  if (elements[0].value) {                  
    elements[0].style.border = 'solid 1px #00FF00';
    alert("Ok");
  } else {
    elements[0].style.border = 'solid 1px #FF0000';
    alert("Preencha o campo Código");
  }
}
<input class="testetxt" type="text"/>
<button onclick="teste();" style="height:20px; width:20px;"> </button>
    
18.05.2018 / 21:13
1

Your script has an error you are using instead of! = and is doing a redundant comparison

function teste() {
  var elements = document.getElementsByClassName("testetxt");
  if (elements.value != null && elements.value !="") {                  
    elements.style.border = 'solid 1px #00FF00;';
    alert("Ok");
  } else{
    elements.style.border = 'solid 1px #FF0000;';
    alert("Preencha o campo Código");
  }
}
    
18.05.2018 / 21:02