Home > Enterprise >  When i remove readonly using key function, it automatically adds the character on the textbox
When i remove readonly using key function, it automatically adds the character on the textbox

Time:03-01

My target is to remove readonly attribute from my textbox after hitting the key "E". It is working but the problem is after I hit "E" it automatically adds on the textbox also. Is there a way to avoid this? Am I missing something? Thank you and have a nice day

$(document).keydown(function(e) {
  if ($(e.target).is('input')) {
    return true
  } else if (e.keyCode == 84) {
    var href = $('#top').attr('href');
    window.location.href = href;
  }

  if (e.keyCode == 69) {

    $("#edit").click();
    $(".removereadonly").attr("readonly", false);
    $('.auto').focus();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="edit">
 button
</button>

<input type="text" id="testingid"  readonly>

CodePudding user response:

You can cancel a jquery event with return false;.

Putting this inside the check for e will only cancel that initial keydown - if the user continues to hold the key down, the input will receive the additional events.

You may like to add additional checks, otherwise any future press of e will also re-focus (unless an input).

Updated snippet:

$(document).keydown(function(e) {
  if ($(e.target).is('input')) {
    return true
  } 
  if (e.keyCode == 69 && $(".removereadonly").length) {
    $("#edit").click();
    $(".removereadonly")
        .attr("readonly", false)
        .removeClass("removereadonly");
    $('.auto').focus();
    return false;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="edit">button</button>
<input type="text" id="testingid"  readonly>

  • Related