Search code examples
jquerykeypress

How can i set the output keyPress to the same input field?


I am trying to get the user keypress output and set it to the same input.

However in my input result I get the output twice. For example, if the user presses d I see Dd. How can I solve this?

$(document).ready(function() {
  $("#test").keypress(function(e) {
    let key = String.fromCharCode(e.keyCode);
    let upperCaseKey = (key.toUpperCase())
    $("#test").val(upperCaseKey);
    $("#test").css("width", "25px")
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text class="myid" id="test" />


Solution

  • <input type=text class="myid" id="test" />
    
    
    
    
    $(".myid").on('keypress', function(evt) {
      $(this).val(function (_, val) {
        return val + String.fromCharCode(evt.which).toUpperCase();
      });
    
      return false;
    });