What is the functionality of the keydown event?

Whenever the input text value is not empty, I want my .removetext div to be displayed, but it's not working correctly. When I type something after the second character, my .removetext gets hidden, but it shouldn't be hidden when the input is not empty.

Where did I go wrong? I think I am misunderstanding the keydown event.

$(document).ready(function() {
      $('.search-hotels').on('input', function() {
        var val = $.trim(this.value);
        if (!val == "") {
          $(".removetext").show(val.length > 0, function() {
            var clear = $(this);
            clear.on('click', function() {
              alert('hey');
            })
          });
        } else {
          $(".removetext").hide();
        }
      });

    });
.main {
      position: relative;
      width: 40%;
    }

    .search-hotels {
      width: 100%;
      padding: 15px;
      border: 3px solid #ccc;
    }

    .removetext {
      position: absolute;
      right: 0;
      top: 25%;
      font-size: 23px;
      display: none;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="main">
      <input type="text" class="search-hotels">
      <div class="removetext">×</div>
    </div>

Answer №1

For an easy input experience, try using the paste feature:

$(function() {
  $('.search-hotels').on('input', function() {
    var val = $.trim(this.value);
    $(".removetext").toggle(val.length>0); // check for non-blank input
  });
  // make sure to place the event handler HERE and not inside the input handler
  $(".removetext").on('click', function() {
      alert('hey');
  });
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels" value="">
  <div class="removetext">&times;</div>
</div>

If you require a callback function, ensure to use show and hide respectively:

$(function() {
  $('.search-hotels').on('input', function() {
    var show = $.trim(this.value).length>0;
    if (show) {
      $(".removetext").show("slow",function() {
        console.log("showing");
      });
    }
    else {
      $(".removetext").hide("slow",function() {
        console.log("hiding");
      });
    }
        
  });
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels" value="">
  <div class="removetext">&times;</div>
</div>

Answer №2

To achieve your desired outcome, consider using the keyup event instead of keydown, and modify your if statement to:

if ($(this).val());

The reason for this change is that using keydown will not capture the updated value with .val as it triggers before the input is fully processed. On the other hand, keyup occurs after the user has entered data, making it more suitable for capturing accurate values.

A more effective approach would be utilizing the input event:

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>

Answer №3

It is important to note that the keydown event is triggered before a character is actually typed, so for accurate results it is recommended to use the keyup event which occurs after the character has been typed.

Furthermore, there is a distinction between !$(this).val() and $(this).val()==""

Instead, consider using if($(this).val()=="")

Answer №4

To capture user input in real-time, it is recommended to utilize the keyup event over key down. While key down registers the pressed key, the input field may not be updated yet. You can extract the value from keydown using the "key" property, but for getting the complete text entered in the input field, it's best to use the keyup event.

Answer №5

You should consider utilizing the keyup event listener in this scenario and it would be beneficial to also check for the length of $(this).val().

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val().length > 0) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>

Answer №6

Make sure to check for $(this).val() instead of checking if it's empty. Additionally, consider using the keyup event instead of keydown as it captures the value after it has been entered.

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>

Answer №7

When the button is pressed, the keydown event fires and the value is not yet updated. To ensure that the input value is updated, use the keyup event which triggers when the button is released...

$(document).ready(function() {
  $('.search-hotels').on('keyup', function() {
    console.log(this,$(this).val());
    if ($(this).val()) {
      $(".removetext").show(function() {
        console.log($(this).attr('class'));
      });
    } else {
      $(".removetext").hide();
    }
  })
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>

Answer №8

Avoid using the keydown event because it lags one keypress behind what is actually typed into the input field's value.

Instead, consider using the oninput event handler (not just keyup as commonly suggested, but as mentioned by @mplungjan). Using oninput allows for accurate tracking of copy/paste events compared to onkeyup.

When reading the input value, use this.value and remember to trim it to remove any unnecessary whitespaces.

$(document).ready(function() {
  $('.search-hotels').on('input', function() {
    if (this.value.trim()) {
      $(".removetext").show();
    } else {
      $(".removetext").hide();
    }
  })
});
.main {
  position: relative;
  width: 40%;
}

.search-hotels {
  width: 100%;
  padding: 15px;
  border: 3px solid #ccc;
}

.removetext {
  position: absolute;
  right: 0;
  top: 25%;
  font-size: 23px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="main">
  <input type="text" class="search-hotels">
  <div class="removetext">&times;</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sticky CSS - A guide to making aside elements fill the entire available height

How can I create a grid layout where the aside is sticky to top: 0 and fills all remaining height (e.g. 100% of height), but when scrolling down, the aside height should be changed to 100% minus the footer's height? Is it possible to achieve this with ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

The bottom margin fails to function as expected

I've been trying to position a loading image at the bottom right of the page, but everything seems to be working except for the margin-bottom. <div id="preload"> <div align="right" style="margin-bottom:40px; margin-right:50px;"> ...

Issue with MUI Autocomplete not showing selected name on initial option selection

I encountered a strange issue with the Autocomplete component from Material UI. Here is the code snippet in question: const [isContactListInitialised, setContactListInitialised] = useState(false); const toggleContactListInitialized = () => { setContactL ...

I'm facing an issue with my 'root' div on ReactJS - it doesn't stretch all the way to the top. Any suggestions on how I can make it expand properly

While I realize this issue has been discussed extensively, none of the suggested solutions have worked for me. As a final attempt to resolve it, I am turning to you all here. The point at which my root div stops is puzzling: I've explicitly defined ...

Visual Studio is refusing to highlight my code properly, intellisense is failing to provide suggestions, and essential functions like go to definition are not functioning as expected

Due to a non-disclosure agreement, I am unable to share any code. However, I am experiencing an issue with Visual Studio not highlighting my code or allowing me to utilize its built-in tools. While I can rebuild the project, I cannot edit or access any fil ...

Steps for customizing the dropdown arrow background color in react-native-material-dropdown-v2-fixed

Currently, I am utilizing react-native-material-dropdown-v2-fixed and I am looking to modify the background color of the dropdown arrow. Is there a way for me to change its color? It is currently displaying as dark gray. https://i.stack.imgur.com/JKy97.pn ...

Fading colored images and backgrounds using Javascript

Although js and html are not my strong points, I am attempting to create two simple effects on a single page. As the user scrolls down the page, I want the background image or color to change as different divs come into view and then move off the screen. ...

Retrieve a targeted tag from the API snippet

I need to extract the IMG SRC tag from the given code: <pod title="Scientific name" scanner="Data" id="ScientificName:SpeciesData" position="200" error="false" numsubpods="1"> <subpod title=""> <plaintext>Canis lupus familiaris</plain ...

Importing vs Referencing Videos in Next.js - What is the Best Practice for Video Integration in Next.js?

I'm looking to use a video as a background in my banner design. Typically, with images in Next.js, I would import them and then pass the import as src (for example: import img from '@images/about-us-page/img.svg'). However, when attempting ...

Tips for creating an onChange function in an input field using jQuery

I am looking to dynamically create inputs where each input has an `onChange` function with a variable. Here is my code: var distinct_inputs = 0; $('.icon1').click( function(){ distinct_inputs = distinct_inputs + 1 ; $('#insert-file&apo ...

Encountering a 404 error indicating that the file cannot be found while attempting to log into an authentication system developed using express and node

Currently, I am in the process of developing a demonstration banking application that facilitates user sign up and sign in functionality using express.js and node.js. The API created accepts POST requests to /signup and /authenticate routes successfully wh ...

Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with Poi ...

"Enhancing web interactivity with AJAX requests and dynamic functionality in web

I'm finding it hard to understand the distinction between Rich Internet Applications and AJAX calls. From what I gather, any application that requires client-side execution can be classified as RIA. So, by this definition, should this website be cons ...

When using PHP's `json_encode()`, don't forget to append a "1" at the

While utilizing json_encode in my project, I have encountered an issue that is perplexing. On one particular page where I make an ajax call, the resulting json seems to mysteriously add a 1 to the end of the string. The output of my return string appears ...

Real-time searching on Laravel using AJAX technology

I'm having trouble with implementing a live search feature in my Laravel 5.4 project. The console is showing an error message: GET http://localhost/bodegasilusion/public/search 500 (Internal Server Error) jquery.js:9392 Despite trying different solut ...

The use of callback functions with Model.findOne() in Mongoose is now deprecated, and will result

Think about this: app.get("/posts/:postId", function(req, res) { const requestedPostId = req.params.postId; Post.findOne({_id: requestedPostId}, function(err, post) { res.render("post", { title: post.title, content ...

Model for handling Node/Express requests

I always saw Node.js/Express.js route handlers as akin to client-side EventListeners such as onClick, onHover, and so on. For example: document .getElementById('btn') .addEventListener('click', function() { setTimeout(functi ...

Integrate a Facebook Like-box within a customized jQuery modal window

I've been working on inserting the Facebook like-box code into my page and trying to display it within a jQuery modal dialog. Here's the code I'm using: <script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>< ...