jQuery in Action
Making GET and POST requests
247
We'll, once again, iterate through all the elements in the matched set; before
we do that, we empty all
<select>
elements in the matched set by calling the
emp-
tySelect()
command that we defined. This removes any options that might be in
the element prior to our adding the new options.
Within the iterator function, we check the tag name of the elements and
ignore all but
<select>
elements. For the elements that survive this test, we iterate
through the data array passed to the command, creating a new
Option
instance
for each array item and adding it to the
<select>
.
This addition is problematic because it must be performed in a browser-
specific fashion. The W3C standard defines the
add()
method so that, in order to
add an option to the end of the
<select>
, a
null
must be passed as the second
parameter to
add()
. We'd think that this would be easily accomplished by omit-
ting the second parameter as in
selectElement.add(option);
But life can't be that simple. The Safari and Opera browsers work equally well
whether the option is omitted or explicit, but Mozilla-based browsers throw a too-
few-arguments exception when the second parameter is omitted. Adding an
explicit
whether the option is omitted or explicit, but Mozilla-based browsers throw a too-
few-arguments exception when the second parameter is omitted. Adding an
explicit
null
as the second parameter doesn't help matters because doing so
causes Internet Explorer to no longer add the new option.
Catch 22!
Because there is no single cross-browser way to perform the operation and no
Because there is no single cross-browser way to perform the operation and no
object to perform detection upon to use the preferred technique of object detection,
we're forced to resort to browser detection. Sigh. At least we have the
we're forced to resort to browser detection. Sigh. At least we have the
$.browser
utility flags to make the detection easy.
Once again, note that the wrapped set is returned as the function's result.
The full implementation of these commands can be found in the file chapter8/
The full implementation of these commands can be found in the file chapter8/
bootcloset/jquery.jqia.selects.js and is shown in listing 8.7.
(function($) {
$.fn.emptySelect = function() {
return this.each(function(){
if (this.tagName=='SELECT') this.options.length = 0;
});
}
$.fn.loadSelect = function(optionsDataArray) {
return this.emptySelect().each(function(){
if (this.tagName=='SELECT') {
Listing 8.7
The implementation of our custom select commands