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
- Which one is considered as a standard practice?
- Is there any merits with any of these methods?
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).
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:
but when you update it, just swap out its contents ( where newSelectElement is the new
<select>
element):You can also use
.on
Before jQuery 1.7,
change()
was simply an short cut forbind("change")
.As of 1.7 however,
on()
has replacedbind("change")
,so change()
is a shortcut for that instead.Therefore the best way would be either;
I prefer the 2nd option as it also can applied automatically to the dynamically generated
DOM
.