12

I am little confused in binding onchange to select. I can see there are multiple ways of doing this.

html

<select id="ddl" onchange="test()"></select>

jquery

$(function(){

    $("#ddl").change(function(){
               return test();
           });

});

or

 $(function(){

    $("#ddl").bind("change", function(){
               return test();
           });

});

Among these 3 methods

  1. Which one is considered as a standard practice?
  2. Is there any merits with any of these methods?
  • http://stackoverflow.com/questions/937039/what-is-the-difference-between-the-bind-and-live-methods-in-jquery help you.. – sasi Feb 26 '13 at 12:45

3 Answers3

17

You can also use .on

$('SELECT').on('change',function(){
   // code
});

Before jQuery 1.7, change() was simply an short cut for bind("change").

As of 1.7 however, on() has replaced bind("change"), so change() is a shortcut for that instead.

Therefore the best way would be either;

$("SELECT").bind("change", function(e) {});
$("SELECT").on("change", function(e) {});

I prefer the 2nd option as it also can applied automatically to the dynamically generated DOM.

Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
2

all mentioned jquery methods seems to be equal, I would suggest using .change() making your code easier to read.

I've experienced that html onchange="" is rewritten by jquery bound events, but multiple calling to jquery .change() will chain the handlers which is usually wanted behavior.

To make the code clean, I'm using html onchange property only in simple programs which I know that will not have multiple event handlers and the code inside is really easy (usually one function).

amik
  • 5,613
  • 3
  • 37
  • 62
0

Instead of rebinding the <select> every time, you're better off just swapping its contents (the list of <option> elements) instead.

So use this as you already are:

$("#ItemsPerPage").change(function(e) { return updatePaging(); });

but when you update it, just swap out its contents ( where newSelectElement is the new <select> element):

function updateItemsPerPage( newSelectElement ) {
    $("#ItemsPerPage").empty().append( newSelectElement.childNodes );
}
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Kapil Gupta
  • 194
  • 5
  • 21