0

I have a <p>element that should contain whatever is written in the <input> box. The <p> does contain everything there is in <input> except the last character.

For example, (not valid JS code)

 if input = Fish 
    then p = Fis

if input = Monster
    then p = Monste

Here is my code

    <head>
        <script>
            window.onload = function()
            {
                document.querySelector('input').addEventListener('keydown', function()
                {
                    document.querySelector('p').innerHTML = document.querySelector('input').value
                });
            }
        </script>
    </head>
    <body>
        <p></p>
        <input type="text" />
    </body>

How do I make the p element contain even the last character in the input?

2 Answers 2

3

By registering to the 'keydown' event, your logic is firing when the key is pressed down, but the input box's value isn't updated until after your finger comes off the button.

Try registering to 'keyup' instead.

<script>
            window.onload = function()
            {
                document.querySelector('input').addEventListener('keyup', function()
                {
                    document.querySelector('p').innerHTML = document.querySelector('input').value
                });
            }
        </script>

Fiddle: https://jsfiddle.net/cb457Lpt/

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

2 Comments

Better event is input.
"Better" is subjective term, but yes it's also an option.
1

If you want to remove the last character from input value, and to add the resulted string in a html element, try this code:

<p id='id_p'></p>
<input type="text" id='id_inp' />
<script>
var id_inp = document.querySelector('#id_inp');
id_inp.addEventListener('input', function(e){
  var str_inp = e.target.value;
  document.querySelector('#id_p').innerHTML = str_inp.replace(str_inp.substr(str_inp.length - 1), '');
});
</script>

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.