How to make the site respond to text? Ex: user X: "hi user X" if not this user "hi unknown user"

Asked

Viewed 61 times

-1

<!doctype html>
<html>
<body>
<input type="text" name="text" id="text"/>
<input type="button" name="button" value="wert" id="button" class="button" Onclick = "wert()"/>

<script>
function wert() {
var o = document.GetElementById('text').value;
var nome = "antonio";
var ok = nome = o;
var ok = true;

if(ok){
alert("oi antonio")
else {alert(oi desconhecido)}
  }

}

</script>

</body>
</html>
  • 2

    This is full of syntax errors. Missing key before the else, quotes in text, parentheses,...

  • 1

    In addition to syntax errors, your condition will always be true, because the ok variable takes a true;

3 answers

2

Hello You can do as follows, I hope to have helped.

<!doctype html>
<html>
<body>
<input type="text" name="text" id="text"/>

<input type="button" name="button" value="wert" id="button" class="button"/>

<script>


function wert() {
var text = document.getElementById('text').value;

	if(text != ''){
		alert('Olá '+text);
	}
	else{
		alert('Olá Usuario Desconhecido');
	}
}

var button = document.getElementById('button');

button.addEventListener("click",function(){
  wert();
});

</script>

</body>
</html>

2

You are overwriting the ok variable, and it will always be true. Also, you are taking the value of the field, but you are not using it. To use the name that is passed by the input, follow an example:

function wert() { 
 var nome = document.getElementById('text').value;
 if (nome) {
   alert(`Oi ${nome}`);
  } else
   alert('Oi desconhecido');
  }

I advise you to study the basics of javascript before integrating it with HTML. I hope I’ve helped!

2

There are syntax and logic errors as already commented above. Revise some concepts and if possible indent the code.

<!DOCTYPE html>
<html>
<body>
   <input type="text" name="text" id="text"/>
   <input type="button" name="button" value="wert" id="button" class="button" Onclick = "wert()"/>

   <script>
      function wert() {

         // Métodos são por padrão definidos com a inicial MINÚSCULA, e faz diferença em linguagens caseSensitive
         var o = document.getElementById('text').value;
         var nome = "antonio";

        /* Em relação a operadores '=' significa atribuição e '==' comparação
         * Nesse caso, se a variável 'nome' for igual à 'o', 'ok' será true, se não false
         */
         var ok = nome == o;

         // As chaves delimitam um bloco de comando, por isso a indentação do código é importante.
         if(ok){
            alert('Oi antonio!');
         } else {
            alert('Oi desconhecido!');
         }

      }
   </script>

</body>
</html>

Browser other questions tagged

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