Since last year when we discussed jQuery in one of our User Group Meeting, I have been amazed by the power of jQuery. A month ago, I also tweet a picture “Say No to JavaScript without jQuery” and that is because with CSS and jQuery we can exploit the power of JavaScript/CSS, by writing just few lines of code, plus it allow you to make your HTML markup clean and independent of script/event logic. If you take a look at the twitpic below, you will observe that markup does not register any event rather the binding on click event has been taken care inside script tag using jQuery selectors.


And that is not the all. To further decouple it, we can use CSS class instead of button Id “btnTest” and then move the JavaScript in .js file. I hope this make sense to you! (if not than don’t worry, just continue reading…)

But today what I am going to share is a real world scenario of how jQuery helped me in observing change in any input element of page.

Usually, we have requirement on web form that when users presses a cancel button after entering any information on page then we have to prompt a cancel confirmation dialog like:

Cancel Dialog

And I really don’t know what is the best way to do this but what I have observed is that developers have done this by registering onchange JavaScript event on every single input element that needs to be tracked down. Something like snippet below:

Observing Change without jQuery

along with some script:

JavaScript without jQuery Library

So what it does is that whenever users enters any text in text input element or change the value of dropdown then it will fire the method SetChangeVariable() which will set value of isChanged to true, which means we need to show cancel confirmation dialog.

Now imagine if I have a page with more than 20-30 fields then I have to go and manually wire the onchange method. Let’s see what jQuery and CSS together offers to us.

Suppose that we have a CSS class element

CSS Element

Then we will assign each element class “TrackChange” that needs to be taken care of as in code snippet below:

Observing Change with CSS

along with some JavaScript that uses jQuery library:

JavaScript with jQuery

What above code does is that when document is ready, that’s what $(document).ready does, its going to select all elements with class assigned “TrackChanged” through one of its selector $(“.TrackChange”) and wired up event of change and set global variable isChanged to true. That’s it!

By using CSS class you can now move the JavaScript in .js file and make your HTML markup clean…

If you don’t like assigning CSS class, another great thing you can do with jQuery is to wire change event on all input elements using input selector:

jQuery Input Selectors

and no need to assign any CSS class! Isn’t that amazing?

That is all for today. Happy Coding!


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *