Reverse the characters added in text field

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 106

Reverse the characters added in text field

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.

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


Similar Topics