Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Show input values in a p tag

I have an input element, what I want to achieve is whenever I type into the input, the characters will be inserted into a p tag and will be displayed. The code I have below partially works. The problem I have with my code is the characters will start to show in the p tag when I type the second character. I want it to start showing after 1st typed character. How can I achieve this?

$('input').keypress(function() {
  if ($(this).val().length >= 0) {
    $('p').html($(this).val())
  }
});

$('input').keyup(function(e) {
  if (e.keyCode == 8) {
    if ($(this).val() == "" || $(this).val() == null) {
      $('p').html('')
    }
    $('p').html($(this).val())
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<p></p>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I think input event is ideal for this case. Also catches copy-paste into the field.

$('input').on('input', function() {
  $('p').html($(this).val())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input />
<p></p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading