Javascript IF and ELSE difficulty - Return result text on screen

Asked

Viewed 40 times

-1

DOUBT: How to make an IF ELSE with javascript to display a text (Ex: Approved) when locating a given word (Ex: Green). My current code is this below, but it’s not working and I can’t find the problem. I’m a beginner with Javascript, so if anyone knows how to help me thank you!

var status_atual = 'Azul'; //

   if (status_atual = "Verde") {
  return 'Aprovado';
} else if (status_atual = "Vermelho") {
  return 'Reprovado';
} else if (status_atual = "Amarelo") {
  return 'Incompleto';
} else if (status_atual = "Azul") {
  return 'Novo';
} else {
  return 'Cor e status não identificados!';
}



I needed to have the result displayed in the table, just as it is done in PHP with the echo function, so for example:

<?php

$status_atual = 'Azul';

   if ($status_atual = 'Verde') {
  echo 'Aprovado';
} else if ($status_atual = 'Vermelho') {
  echo 'Reprovado';
} else if ($status_atual = 'Amarelo') {
  echo 'Incompleto';
} else if ($status_atual = 'Azul') {
  echo 'Novo';
} else {
  echo 'Cor e status não identificados!';
}

?>

Example of the IF ELSE result being displayed in the table:

inserir a descrição da imagem aqui

  • Note that both JS and PHP code have problems.

  • Comparison operator is == or ===. The = is itself an allocation operator.

1 answer

1

In many programming languages, as well as in javascript, the operator = is not a comparator, but assigns the value to a variable.

In this case, substitute it, wherever you are making comparisons, for ==.

In Javascript there is also the operator ===. Try to read about the difference between the 2.

Follows fiddle of example: https://jsfiddle.net/jhtcsLw7/.

  • Okay, thanks for the answer. I need to put this if Else inside this other heheheh code, do you have any idea how it would be done? {&#xA; "render": function ( data, type, row ) {&#xA; return 'CODIGOIFELSEAQUI';&#xA;&#xA; },&#xA; "targets": 3&#xA; },

  • I tried to do that, can you take a look? https://jsfiddle.net/h9e1mkcn/

  • @Brunofariasprogramming created a fiddle as an example. Note that in the fiddle you sent you changed the = in atribuição also.

  • I agree with @tvdias. I know that the question clearly mentions that you want to use a if/else. However, in these cases I think it would be more appropriate to use a switch/case. Here is the suggestion.

Browser other questions tagged

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