Page 1 of 1

Reverse the characters added in text field

Posted: 27 Oct 2020, 07:30
by Marius
I have the following html and JavaScript code. An input text box and a button.

Code: Select all

<input type='text' id='backwards-input'>
<button id='backwards-button'>Button</button>
<p id='backwards-container'></p>

<script>
const bkinp = document.getElementById('backwards-input');
const bkbtn = document.getElementById('backwards-button');
const revtxt = document.getElementById('backwards-container');
</script>
How can I make, when I press the button, the text that is added in the input box be displayed into the <p> element, but in reverse order?
For example, if in the input is "abc 123", the text "321 cba" should be added into the <p> element from my code.

Reverse the characters added in text field

Posted: 27 Oct 2020, 07:45
by Admin
Try use and study the following code:

Code: Select all

<input type='text' id='backwards-input'>
<button id='backwards-button'>Button</button>
<p id='backwards-container'></p>

<script>
function backwards(inp, rev) {
  const backwardsInput = inp.value.split('').reverse().join('');
  rev.textContent =  backwardsInput;
}

const bkinp = document.getElementById('backwards-input');
const bkbtn = document.getElementById('backwards-button');
const revtxt = document.getElementById('backwards-container');
bkbtn.addEventListener('click', ()=>{ backwards(bkinp, revtxt)});
</script>
Demo

321 cba