JonasSH
JonasSH

Reputation: 206

My function that detects keydown and value does not work

So I have an input bar, where text can be typed in.

I am trying to get the console.log to run as soon as the user clicks on backspace and because of that leaves the input with no value.

Right now the console.log only runs if the backspace is clicked while there isn't any value in the input.

GOAL - The console should ONLY run if clicking on backspace CAUSES the input to be empty.

$("#friendsNames").keydown(function(event){
          if (event.keyCode == 8) {
            if ($("#friendsNames").val() == "") {
              console.log("Works!");
            }
          }
        });
<input type="text" name="namesOfFriend" id="friendsNames" value=""  />

Upvotes: 0

Views: 63

Answers (4)

Alnitak
Alnitak

Reputation: 339896

I'd recommend not tracking key strokes at all, but monitoring the content of the box using the input event which fires when that content changes:

$("#friendsNames").on('input', function(event) {
    if (this.value.length === 0) {
        console.log("Works!");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value=""  />

This ensures that any interaction that results in the input becoming empty will trigger your code.

Upvotes: 2

Milan Chheda
Milan Chheda

Reputation: 8249

As I understand, you want console.log to execute only where this is any value in the input box, else it shouldn't execute, right? Based on this, below is the code:

$("#friendsNames").on('input', function(){
          var inputValue = $(this).val();
          if(inputValue.length == 0)
              console.log("Works!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="namesOfFriend" id="friendsNames" value=""  />

Upvotes: 0

anilviradiya
anilviradiya

Reputation: 139

$("#friendsNames").keypress(function(event) {
  if (event.keyCode == 8 || $(this).val() != "") {
    alert("Works!");
  }
});

Upvotes: 0

Shubham Baranwal
Shubham Baranwal

Reputation: 2498

Try to make event on keyup coz if input field empty and you're going to enter first character in it console.log() calls. So try this code or go through mention link JSFiddle

JAVASCRIPT Code -

$("#friendsNames").keyup(function(event) {
  if (event.keyCode == 8 && $(this).val() == "") {
    console.log("Works!");
  }
});

Upvotes: 0

Related Questions