Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move text between two boxes using two buttons?

Given this:

function moveRight() {
  var tmp = document.getElementById("lefttext").innerText;

  if (document.getElementById("lefttext").innerText != null) {
    document.getElementById("lefttext").innerText = document.getElementById("righttext").innerText;
    document.getElementById("righttext").innerText = tmp;
  }
}
<table width="250px" border="1">
  <tr>
    <td>
      <div id="lefttext">Placeholder</div>
    </td>
    <td>
      <button onClick="moveRight()" id="moveright">Right</button>
      <button onClick="moveLeft()" id="moveleft">Left</button>
    </td>
    <td>
      <div id="righttext"></div>
    </td>
  </tr>
</table>

I am trying to make use of two buttons (left, right) to move the placeholder text between the left and right of the table column. Currently, I am testing on one side (moving to the right only) but the method I came up with allow the text to be swapped between the two location instead of just moving it to the right and stop.

Isn't the "IF" suppose to prevent this if my "lefttext" innerText is null (empty)? What is the correct approach I should take?

Thanks.

like image 959
SunnyBoiz Avatar asked May 10 '26 21:05

SunnyBoiz


1 Answers

From my comment

There is a difference between null and empty (empty string). Though they are both equivalently "falsey" they are not the same thing. Try logging out document.getElementById("lefttext").innerText with console.log and see what you get. You don't get null you get an empty string and that is != to null,

You can change your original

if (document.getElementById("lefttext").innerText != null) to this

if (!!document.getElementById("lefttext").innerText) The !! will take care of null, empty string and undefined

function moveRight() {
  var tmp = document.getElementById("lefttext").innerText;

  if (!!document.getElementById("lefttext").innerText) {
    document.getElementById("lefttext").innerText = document.getElementById("righttext").innerText;
    document.getElementById("righttext").innerText = tmp;
  }
}
<table width="250px" border="1">
  <tr>
    <td>
      <div id="lefttext">Placeholder</div>
    </td>
    <td>
      <button onClick="moveRight()" id="moveright">Right</button>
      <button onClick="moveLeft()" id="moveleft">Left</button>
    </td>
    <td>
      <div id="righttext"></div>
    </td>
  </tr>
</table>
like image 145
gforce301 Avatar answered May 13 '26 13:05

gforce301



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!