user3871
user3871

Reputation: 12718

jquery `on change` doesn't recognize when you set textbox value programmatically

I want to clear out a textbox when I call:

$('#textBox').val(''); or $('#textBox').empty();

Originally, when I would manually backspace and delete the text out of the text box, the on change function would fire. If I run $('#textBox').val('') above, on change does not fire:

$(document).ready(function() {
    $('#textBox').on('change', function(){

Why is this?

Upvotes: 1

Views: 1168

Answers (3)

nietonfir
nietonfir

Reputation: 4881

It's not jQuery that doesn't fire the event, it's the browser. If you look it up in the specs you'll see the definition of the change event:

change

The change event occurs when a control loses the input focus and its value has been
modified since gaining focus. This event is valid for INPUT, SELECT, and
TEXTAREA. element.

    Bubbles: Yes
    Cancelable: No
    Context Info: None

As already posted, your problem can be mitigated by triggering the event manually via trigger().

Upvotes: 1

Kristijan
Kristijan

Reputation: 5885

Use trigger, like this:

$("#testBox").val("").trigger("change");

Upvotes: 4

ATOzTOA
ATOzTOA

Reputation: 35950

When you change the value programmatically, just trigger the change event using trigger.

$("#myid").trigger("change");

Upvotes: 1

Related Questions