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>
CodePudding user response:
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>
CodePudding user response:
You just use keyup function.
$('input').keyup(function() {
if ($(this).val().length >= 0) {
$('p').html($(this).val())
}
});
$('input').keydown(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>