Implementing OnChange and OnKeyUp Event Using jQuery (Select Box)

Posted in Web Development on 21 March 2011 3 comments

Of course there is nothing wrong if you implement onChange event using the traditional way, that is by adding onchange=”" attribute to the HTML element. However, your codes can be better in some ways if you do it using jQuery.

Advantage of Implementing OnChange Event using jQuery

  • More clean & organised. You don’t have to add inline attribute to the HTML element. The onchange event is added using jQuery that can targets any elements you want. Your jQuery scripts can be placed externally (of course), just like external CSS, more organised, easy to reuse and to be edited later on.
  • jQuery is able to automatically run the event once after the page load. Please visit the demo page for more information about this.

The Codes

?View Code JAVASCRIPT
<script type="text/javascript">
  $(function () {
 
    $('#dropdown').bind('change keyup',function () {
 
      //get value of selected option
      var value = $(this).children("option:selected").attr('value');
 
      // do something here
 
    }).change();
 
  });
</script>
 
<select id="dropdown">
  <option value="Item 1">Item 1</option>
  <option value="Item 2">Item 2</option>
  <option value="Item 3">Item 3</option>
  <option value="Item 4">Item 4</option>
</select>

Onchange event is called change() in jQuery. We include jQuery keyup() event (onkeyup event in JS) too so that it can detect the change when user change their selection using keyboard arrows. For more information and real example, please visit the demo page below.

The Example Page

Onchange Event Using JQuery – Example & Demo

This example page demonstrates 2 different ways to add onchange event to a select box. One using the traditional way, another using jQuery. Feel free to view the source to learn more and use the codes wherever you want.

That’s it

Of course, the downfall of having jQuery in your page are increased bandwidth and page loading time, to load the extra 60kb of javascripts. However, if you are already using jQuery in your website, this is definitely the method you should go for.

 

Posted by Zen on 21 March 2011 • 24,770 visits 3 comments
Tags :


or Subscribe to specific category only :




  - 3 Comments


Brillz says:

Still quite bad with jQuery but these small tips help tremendously! also love that you include a example page instead of a screenshot gives you so much more to go on! Keep it up :)

Mike says:

Hiya,

Were you aware this does not work in Chrome?

Mike

Zen says:

I just tried again and it works for me. In fact chrome is my main browser

Leave a Reply

You must be logged in to post a comment.

Previous Post
«
Next Post
»