Dark
Dark

Reputation: 124

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

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" class="removereadonly auto" readonly>

Upvotes: 2

Views: 236

Answers (1)

fdomn-m
fdomn-m

Reputation: 28621

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" class="removereadonly auto" readonly>

Upvotes: 1

Related Questions