jQuery val( val ) and the absence of onChange firing

Some coworkers and myself have run into some confusion using the val( val ) function of jQuery to set the value of a control, and finding that the control's onChange event does not fire.

First of all, onChange is implemented differently between Firefox and IE.  In IE, onChange for a select box fires right as the value of the select is changed.  Some say that this implementation is incorrect and that the onChange event is supposed to fire after the control looses focus.  Firefox implements the event the other way.  I've not checked the W3C specs to see which is correct, because frankly I don't care. What I do care about is that I have to deal with the inconsistency.

So taking the implementation into consideration, when you want to set the value of a control using $("myInput").val(newValue);, the onChange not firing makes sense. We're not using val to tell the form to set the value of the control and then make it loose focus.  Perhaps onChange should have been named OnAfterChange instead, but that's besides the point.

To get the behavior we're looking for, set the value then fire the onChange event of the control, we have to call .change() after val( val ).

        function setViajQuery() {
            $("#myInput").val("1");
            $("#myInput").change();
        }

This gives us the behavior we're looking for.

We could easily wrap this in a function to use whenever we're expecting onChange to be fired:

        function setValAndFireOnChange(jQueryObj, newVal) {
            jQueryObj.val(newVal);
            jQueryObj.change();
        }
 
        function setViajQuery() {
            setValAndFireOnChange($("#myInput"), "1");
        }
 

Alternatively, let's extend jQuery:

        (function($) {
            $.fn.valChange = function(newValue) {
                return this.each(function() {
                    var obj = $(this);
                    obj.val(newValue);
                    obj.change();
                });
            };
        })(jQuery);

The code is the same, but instead of the calling syntax being setValAndFireOnChange($("#myInput"), "1");, we can have the same effect gracefully:

            $("#myInput").valChange("1");

The benefit of extending jQuery is that we can respect jQuery's chaining:

            $("#myInput").valChange("1").css("background","blue");


Posted by: Jeff
Posted on: 6/5/2009 at 10:52 PM
Tags:
Actions: E-mail | Kick it! | DZone it! | del.icio.us
Post Information: Permalink | Comments (35) | Post RSSRSS comment feed

Comments

Russell Heimlich United States

Tuesday, August 11, 2009 10:48 PM

Russell Heimlich

Couldn't you just use the onblur event handler rather than onchange?

Citizen Ecodrive United States

Thursday, November 05, 2009 10:41 AM

Citizen Ecodrive

Couldn't you just use the onblur event handler rather than onchange

Jeff United States

Monday, November 09, 2009 6:09 PM

Jeff

Good points guys, the reason I had to come up with this solution was that onblur occurs on loss of focus, and in this situation, there was no loss of focus, because the value of the control was being set via code.

acai berry lose weight United States

Wednesday, February 17, 2010 9:08 AM

acai berry lose weight

There is more to life than increasing its speed.

teeth whitening free kit United States

Wednesday, February 17, 2010 9:25 AM

teeth whitening free kit

Questions provide the key to unlocking our unlimited potential.

colorado springs mortgage United States

Thursday, February 18, 2010 10:56 AM

colorado springs mortgage

This really is a amazing posting, i'm happy I ran across. I've been seeking visitor writters for my blogs so if you ever decide thats something you are interested in please feel free to contact me. I will be back to look at out more of your articles later!

SEO Company United States

Thursday, March 18, 2010 9:57 AM

SEO Company

Great detailed information, I ll be visiting you more frequently, here is very interesting information.

SEO Services India United States

Friday, March 19, 2010 7:38 AM

SEO Services India

Its really nice to read the post and is very beneficial for me in future keep it updating..

PARKING NEW YORK United States

Wednesday, March 24, 2010 2:48 PM

PARKING NEW YORK

Fantastic information given about fire fox and applications post on your blog. Thanks for sharing.We will look forward for your future updates.

SEO services United States

Thursday, April 01, 2010 4:54 AM

SEO services

Thanks for sharing...

miami mortgage company United States

Monday, April 05, 2010 11:03 AM

miami mortgage company

There are very few people in this world who gives such tremendous views. I appreciate your work and hopping for some more informative posts.

Million abstauben United States

Tuesday, April 06, 2010 9:36 PM

Million abstauben

Well, the post is really the freshest on this worthy topic. I fit in with your conclusions and will thirstily look forward to your future updates. Just saying thanks will not just be sufficient, for the wonderful clarity in your writing. I will right away grab your rss feed to stay informed of any updates. Solid work and much success in your business enterprize!

PROFESSIONAL ORGANIZER MARYLAND United States

Wednesday, April 07, 2010 10:11 AM

PROFESSIONAL ORGANIZER MARYLAND

Thanks for the detailed article about jQuery val( val ) and the absence of on Change firing i was waiting for such post as i was in need of it and also thanks for the code it helped  me a lot.

chatroulette clone United States

Thursday, April 08, 2010 2:43 PM

chatroulette clone

Looks like you are a professional in this field. You managed to outline main issues here! Thanks for doing it for us!

bike insurance United States

Saturday, April 10, 2010 2:17 PM

bike insurance

Hello, possibly you could assist me? I see u are using blogengine on your website. I recently decided to make a blog for myself and i am  trying to use a wordpress blog. I read about blog engine and i was thinking maybe you might know where i may be able to find very good training or videos on how to use it properly? Thanks for the assistance

Waffelrezepte Germany

Sunday, April 11, 2010 2:29 PM

Waffelrezepte

Wonderful article. I'am not the one who often comment on blog arcticles, but this post is really great. Thx, your blog will be subscribed. Regards Waffelrezepte

Shooting games United Kingdom

Thursday, April 15, 2010 9:06 AM

Shooting games

Thank you for the great article.
Those samples with the specified information helps us a lot.

Immunity, and Allergic Inflammation United Kingdom

Friday, April 16, 2010 5:09 AM

Immunity, and Allergic Inflammation

Substantially, the article is in reality the sweetest on this precious topic. I harmonise with your conclusions and will thirstily look forward to your upcoming updates.

Buying A Used Car Tips Thailand

Friday, April 16, 2010 5:09 AM

Buying A Used Car Tips

This post give me lots of great information regarding , both of which we all need!b Keep 'em coming

car games United States

Saturday, April 17, 2010 11:23 PM

car games

How you manage to call when implement this part?
.change() after val( val ).

Argentina travel United States

Sunday, April 18, 2010 5:07 PM

Argentina travel

I definitely enjoyed every little bit of it. I have you bookmarked your site and grab your rss feed.

adjustable mattress United States

Monday, April 19, 2010 4:20 AM

adjustable mattress

Hi - This is by far the best looking site I’ve seen. It was completely easy to navigate and it was easy to look for the information I needed. Fantastic layout and great content! Every site should have that. I put a link to your blog at my site, hope you dont mind?

Beds United Kingdom

Monday, April 19, 2010 9:22 AM

Beds

Hmm..i really enjoyed reading your article.Keep sharing.

Hier Artikelverzeichnis United States

Wednesday, April 21, 2010 10:25 PM

Hier Artikelverzeichnis

Thanks for taking this opportunity to talk about "codingreflection.com | jQuery val( val ) and the absence of onChange firing",  I benefit from learning about this subject. If possible, as you gain data, please update this blog with new information. Thanks, Hier

Hier Artikelverzeichnis United States

Thursday, April 22, 2010 1:04 AM

Hier Artikelverzeichnis

Thanks for taking this opportunity to talk about "codingreflection.com | jQuery val( val ) and the absence of onChange firing",  I benefit from learning about this subject. If possible, as you gain data, please update this blog with new information. Thanks, Hier

Watch Hot Movies Online United States

Thursday, April 22, 2010 11:22 AM

Watch  Hot Movies Online

Have you had problems with spammers?  I also use Blog Engine and I have some great anti-spam practices; please visit me if you are interested in an exchange of practices.

DELL Studio XPS 16, Studio XPS 1640 Laptop Battery

DELL Studio XPS 16, Studio XPS 1640 Laptop Battery

Haarentfernungen United States

Saturday, April 24, 2010 6:12 PM

Haarentfernungen



fast cash loan United States

Tuesday, April 27, 2010 4:07 AM

fast cash loan

I'm happy to have found your very good article! I agree with some of your readers and will eagerly look forward to your coming updates. Just saying thanks will not just be adequate, for the wonderful lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Good work and much success in your business efforts.

Rapidshare United States

Tuesday, April 27, 2010 10:26 PM

Rapidshare

I\'m happy I found this blog, I couldnt discover any info on this subject matter prior to. I also run a site and if you want to ever serious in a little bit of guest writing for me if possible feel free to let me know, i\'m always look for people to check out my site. Please stop by and leave a comment sometime!

Geld sparen United States

Sunday, May 02, 2010 9:34 PM

Geld sparen

Only want to say your article is stunning. The lucidity in your post is simply impressive and i can take for granted you are an expert on this field. Well with your permission allow me to grab your rss feed to keep up to date with future post. Thanks a million and please keep up the a uthentic work.

tattoo removal cream United States

Tuesday, May 04, 2010 4:16 AM

 tattoo removal cream

Attractive post. I just stumbled upon your blogpost and wish to say that I have really enjoyed analysis your blog posts. Any way I'll be subscribing to your feed and I expect you post again shortly.

Rapidshare Search engine United States

Tuesday, May 04, 2010 7:00 PM

Rapidshare Search engine

Top Rapidshare Search engine

Pasadena Wedding Venue United States

Tuesday, May 04, 2010 8:12 PM

Pasadena Wedding Venue

good post, lots of helpful information, very well written.

quick cash United States

Friday, May 07, 2010 12:17 AM

quick cash

Hello webmaster, your blog's theme is nice and loving it. Your blog posts are totally great. Please continue this great work. Take Care...

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading