Miair
Miair

Reputation: 3

JavaScript - On Button click, Toggle text problem

I have such a problem: I need to create a button that will toggle my text. I did it, but it changes only one time (From cat to dog), but how can I toggle, so that it will change from cat to dog and dog to cat until stop button is clicked.

<p id="ryiaf"> CAT   
<form action="script.js">  
<input onclick="ryiaf.innerText = 'DOG'" type="button" value="CHANGE YOUR TEXT">
</form>

Upvotes: 0

Views: 127

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can toggle/swap text easily with button click like this way-

function toogleText() {
  var x = document.getElementById("ryiaf");
  if (x.innerHTML === "CAT") {
    x.innerHTML = "DOG";
  } else {
    x.innerHTML = "CAT";
  }
}
<p id="ryiaf"> CAT   
<form action="script.js">  
<input onclick="toogleText()" type="button" value="CHANGE YOUR TEXT"/>
</form>

DEMO: https://www.w3schools.com/howto/howto_js_toggle_text.asp

Upvotes: 0

Faisal Rahman Avash
Faisal Rahman Avash

Reputation: 1256

You need to implement the logic for changing back and forth. Maybe something like this:

<p id="ryiaf"> CAT   
<form action="script.js">  
<input onclick="ryiaf.innerText = (ryiaf.innerText == 'DOG' ? 'CAT' : 'DOG')" type="button" value="CHANGE YOUR TEXT">
</form>

Now, for better code readability, I'd suggest an onclick function in your script file like this:

function handleClickChangeTxt() {
  if (ryiaf.innerText == 'DOG') ryiaf.innerText = 'CAT';
  else ryiaf.innerText = 'DOG';
}
<p id="ryiaf"> CAT   
<form action="script.js">  
<input onclick="handleClickChangeTxt()" type="button" value="CHANGE YOUR TEXT">
</form>

Upvotes: 2

Related Questions