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

Updating files in a Next.js project and automatically refreshing the page without the need to rerun 'npm run'

For a while now, I've been developing websites using a traditional LAMP stack with javascript (including jQuery) for the frontend. Recently, I decided to explore using javascript for the backend as well and started learning next.js. In the older meth ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

Converting JSON to jQuery array within the MVC ASP.Net framework

Apologies for the lengthy question. I just want to ensure clarity in my query. The JSON result from my Controller is as follows:- public JsonResult Top7Video() { db.Configuration.ProxyCreationEnabled = false; var result = (from v in ...

When using JSX, it's important to wrap adjacent elements within an enclosing tag to avoid errors. Make sure to properly wrap the JSX tags to

import React, { useState } from 'react'; import ReactDOM from 'react-dom'; function DisplayData(props) { //creating the DataList const dataList = data.map(data => ( <><span>{data.name}</span> nbsp; <span> ...

Exploring the world of XML parsing with iText

I am curious to learn whether it is feasible to modify the font, color, and size while converting HTML to PDF using xmlWorker.parser. Thus far, I have successfully parsed the input as is, but now I am seeking ways to customize the font, size, color, and ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Creating a custom button to perfectly fit the contours of its content with Font Awesome 5

Can the shape of a button be altered to match its content? Specifically, I am using the "fa-trash-alt" icon and have a button with hover effects that I only want to apply to the icon itself rather than the entire button. Button: <button type='but ...

Creating a responsive image within a panel using Bootstrap

I've been struggling to make a responsive image fit inside a panel while maintaining its aspect ratio and ensuring none of it gets cut off. I've attempted various CSS tweaks with no success. My setup involves Bootstrap along with React.js using r ...

Using Mapbox GL JS to Showcase Latitude and Longitude Coordinates

I successfully added a feature to display the LAT LON readout of the cursor location on my website by following the tutorial provided in This Mapbox GL JS Tutorial However, the output I receive is in this format: {"lng:-74.949147382928,"lat":40.438292204 ...

Setting up CSS Flexbox so that the first child element is the same height as the

I am striving to ensure that when the layout switches to mobile, the image block matches the height of the title and content blocks. The layout is quite complex; it functions correctly in desktop view with the title block at the top full-width. I suspect ...

Using d3 to showcase pictures sourced from a csv file

Having recently embarked on a journey to learn javascript, d3, and the polymer project, I am facing a challenge that I hope to get some guidance on. After successfully parsing a csv file containing image information and creating an array specifically for ...

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...

Text "movement/vibration" in screen when adjusting dimensions in Firefox for Mac

I am currently involved in a project centered around showcasing a variety of fonts to users for them to experiment with, allowing them to adjust size and spacing using sliders. While the functionality works seamlessly on Chrome and Safari, a peculiar issu ...

Insert an HTML element or Angular component dynamically when a specific function is called in an Angular application

Currently, I am working on a component that contains a button connected to a function in the .ts file. My goal is to have this function add an HTML element or make it visible when the button is clicked. Specifically, I would like a dynamic <div> elem ...

Using jQuery to smoothly animate a sliding box horizontally

Is there a way to smoothly slide a div left and right using jQuery animation? I have been trying to achieve this by implementing the code below, which can be found in this fiddle. The issue I am facing is that every time I click on the left or right butto ...

Exploring the possibilities of custom query pagination and Ajax in Wordpress

My Wordpress website has custom category and single pages with a unique query. The pagination is set up to load posts on the same page, which works fine on the homepage. The issue arises when trying to use pagination in single pages and categories using & ...

JQuery class for swapping elements upon scrolling

I am currently working on a navigation bar that changes classes to create a fading effect for the background. The approach I have taken involves targeting the window itself and monitoring the scroll position of the user. If the user scrolls down more than ...

Despite implementing the necessary middleware, the CSS file still refuses to load

My CSS files are not loading properly. When I inspect the element (F12) and go to Networks, my CSS file is not visible. I have added the middleware: app.use(express.static(path.join(__dirname, '/public'))); and required the path above it. I ha ...

Retrieve the `access_token` attribute from local storage

I have stored the token in local storage using: localStorage.setItem('token', JSON.stringify(res.data)). Now, I am attempting to retrieve the access_token property. JSON.parse(localStorage.getItem(token['access_token'])) An error is o ...