0

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>

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.