Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery.val( value ) does not dispatch any event from the DOM element?

When we use the method jQuery.Val( value ) over a DOM element to change its value.

shouldn't the element dispatch an event informing that its value has changed? -I though the event 'change' was going to be dispatched.

If it shouldn't why?

Live Demo

like image 392
SDReyes Avatar asked Oct 18 '10 17:10

SDReyes


People also ask

What does VAL () do in jQuery?

The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.

Does jQuery Val trigger change event?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.

How can get input tag value in jQuery?

jQuery val() method is used to get the value of an element. This function is used to set or return the value. Return value gives the value attribute of the first element.


1 Answers

It's not dispatched, this just doesn't happen when it's programmatically changed. You are however free to fire the event when needed like this:

$('#Anne').val('Jenny').change();

You can test it here.

The reasoning? If the user changed something you may need to react, but if you changed something then you know what happened, and firing an event handler may be completely wasteful...so it's up to you to call that event handler if it's needed.

like image 52
Nick Craver Avatar answered Sep 21 '22 13:09

Nick Craver