Javascript + CSS : Doubt about Value or textContent

Asked

Viewed 48 times

3

I made a condition that is not respecting the content of text.
Follows 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

2 answers

1

In your script there is an error you’re using =! instead of != and you’re making 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");
  }
}
  • My God, forgive my stupidity !!

  • 1

    rsrs td well, sometimes I spend hours trying to find the error and it was just a dot and comma

1


There are several problems in your code besides the ones @Marcos Brinner cited.

One of them is the style value, which cannot have the semicolon:

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

The ; within quotation marks invalidates the value of style and will have no effect.

Another problem is how to select elements by class:

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

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

elements[0]

Another thing is that you can omit the != 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>

  • I understood, in this case it would have to be by Classname to test a thing, because it was unique element and would not need to put an array, but I understood the errors, worth dvd <3

Browser other questions tagged

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