seMikel
seMikel

Reputation: 366

Basic jQuery listener

I realise this is a very dumb question, but I can't seem to understand how to get a jQuery listener to work. I've added the scripts to the html header

<script src="js/http_code.jquery.com_jquery-2.0.0.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/calc.js"></script>

Where I have an input field

<input type="text" size="19" id="infield">

And in the .js file I have the following

    $('#infield').keydown(function(){
        alert("Alert");
    });

But when I write anything into the text field, nothing happens, can somebody tell me where I messed up?

Upvotes: 1

Views: 49

Answers (4)

Ganov13
Ganov13

Reputation: 367

You should use ready state (wait for Jquery to be load) then i advice you to use $.on() method if you'll lately modify DOM:

$(function () {
     $("body").on('change','#infield', function(){alert("Alert");});
});

Upvotes: 0

Kevin Kulla
Kevin Kulla

Reputation: 460

You can use the keypress jquery function

$('#infield').keypress(function(){
  alert("Alert");
});

fiddle: https://jsfiddle.net/kekyafq1/

Upvotes: 0

Gopikrishnan
Gopikrishnan

Reputation: 194

The same code is working here. Double check your jquery file path and other things. Also, check your console for any error messages.

    $('#infield').keydown(function(){
        alert("Alert");
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="19" id="infield">

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

You need to enclose this inside a document.ready event

$( document ).ready( function(){
    $('#infield').keydown(function(){
        alert("Alert");
    });
} );

Upvotes: 3

Related Questions