Swap button text by clicking

Asked

Viewed 84 times

0

I wonder how I can change the text of the button every time I click on it, as if it were a list-group when click it opens and closes, I made this code:

function trocarFlecha()
{
  var x = document.getElementById('btnImage').value;
  if (x = "Imagem  ˅") {
    document.getElementById('btnImage').innerHTML = "Imagem  ˂"; 
  } else {
    document.getElementById('btnImage').innerHTML = "Imagem  ˅";
  }
}

And added a onclick="trocarFlecha()" on the button and it changes only once but I wanted to do it dynamically, making it every time I click it change.

  • And what is the text that should be displayed in the second click?

  • @Andersoncarloswoss In the second click it would return to the original text, for example if the button is equal to Image and when clicked it will turn Video, when clicking again on the same button it turns Image again

  • In his if, should be x == ..., not only x = ....

  • I made the switch but it didn’t work even in the first click

1 answer

-2

Exchange the = for === in:

if (x = "Imagem ˅") {
    ....
}

EDIT: Do it like this,

var cliquei = false;
function trocarFlecha()
{
  var x = document.getElementById('btnImage').value;
  if (cliquei = !cliquei) {
    document.getElementById('btnImage').value = "Imagem  ˂"; 
  } else {
    document.getElementById('btnImage').value = "Imagem  ˅";
  }
}
  • I made the switch but it didn’t work even in the first click

  • It has two spaces right between Imagem and ˅?

  • Yeah, it’s not to get too close

  • I edited my solution proposal.

  • It worked! Thank you very much :D

  • I re-edited the solution proposal.

Show 1 more comment

Browser other questions tagged

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