Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery keyup function not executing

Tags:

html

jquery

input

I have this code :

<script>
     $('#searchInput').keyup(function() {
               alert('Handler for .keyup() called.');
     });
</script>

and this input :

<input id='searchInput' type='text' placeholder='Search other alumni users' />

but when I press a key, the alert doesn't come up... I've included the jQuery script already.

like image 858
omerjerk Avatar asked Jan 19 '13 16:01

omerjerk


People also ask

Why is Keyup not working?

keyup / keydown seem to only work on elements that are present at document. ready . If you are triggering your event from elements that were altered or injected post pageload, these events will not fire.

What is Keyup and Keydown in jQuery?

jQuery supports 3 types of keyboard events and which we are : keyup(): Event fired when a key is released on the keyboard. keydown(): Event fired when a key is pressed on the keyboard. keypress:() Event fired when a key is pressed on the keyboard.

How do I delay a Keyup event?

This is done to ensure that the variable doesn't contain any pre-existing timeout before assigning a new timeout to it. Thereafter, a new timeout is created with the setTimeout() method to add the delay after the keypress() function which generates the desired effect i.e. keyup with a delay.


3 Answers

Change your code to

$(function(){ // this will be called when the DOM is ready
  $('#searchInput').keyup(function() {
    alert('Handler for .keyup() called.');
  });
});

to ensure the DOM element exists when you build the jQuery set.

like image 181
Denys Séguret Avatar answered Oct 09 '22 22:10

Denys Séguret


$(document).ready(function() {
  $('#searchInput').keyup(function() {
    alert('Handler for .keyup() called.');
  });
});

Or

$(function() { 
  $('#searchInput').keyup(function() {
    alert('Handler for .keyup() called.');
  });
});
like image 9
Anujith Avatar answered Oct 09 '22 20:10

Anujith


keyup/keydown seem to only work on elements that are present at document.ready.

If you are triggering your event from elements that were altered or injected post pageload, these events will not fire.

Finding or creating a parent of the element to be watched that's present on load then setting the event to trigger from that parent element can bypass this.

like image 4
Dr-Zee Avatar answered Oct 09 '22 22:10

Dr-Zee