Ehsan
Ehsan

Reputation: 12959

Change event doesn't working when input text change?

This is my code:

<input type="text" id="x">
$(document).ready(function(){
    $("#x").onchange(function(){
        alert("x");
    })
});

But id doesn't work. What is problem?

Upvotes: 1

Views: 3792

Answers (4)

Jai
Jai

Reputation: 74738

change this:

$("#x").onchange

to this:

$("#x").change  

There is a .on() listner, so this can also be used:

$("#x").on('change', function(){
   alert("x");
})

You have a jQuery object and you have to bind the jQuery methods only. And change event on input[type=text] works when you off the focus out of it.

Upvotes: 2

Toby
Toby

Reputation: 1548

$.onchange is not a function. You are getting confused between native JavaScript, which allows

<input onchange="doSomething()"/>

and jQuery, which requires

$(selector).on("change",function(){...});

The correct function is $.on(event) where event is a string. In this case you need

$("#x").on("change",function(){..});

Upvotes: 0

Hearner
Hearner

Reputation: 2729

Because onchange is javascript. In jquery it's change

$("#x").change(function(){
                    alert("x");
                })

or

$("#x").on('change',(function(){
                    alert("x");
                })

But to trigger it you should change focus

Upvotes: 0

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

Use .change() event instead of .onchange() event in jquery.

$(document).ready(function(){
  $("#x").change(function(){
    alert("x");
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<input type="text" id="x">

Upvotes: 0

Related Questions