Fix for incorrect options being selected (noticed same problem with radio/checkbox...
[jquery.git] / src / attributes.js
1 jQuery.fn.extend({
2         attr: function( name, value ) {
3                 var elem, options, isFunction = jQuery.isFunction(value);
4
5                 if ( typeof name === "string" ) {     // A single attribute
6                         if ( value === undefined ) {        // Query it on first element
7                                 return this.length ?
8                                         jQuery.attr( this[0], name ) :
9                                         null;
10                         } else {                            // Set it on all elements
11                                 for ( var i = 0, l = this.length; i < l; i++ ) {
12                                         elem = this[i];
13                                         if ( isFunction )
14                                                 value = value.call(elem,i);
15                                         jQuery.attr( elem, name, value );
16                                 }
17                         }
18                 } else {                              // Multiple attributes to set on all
19                         options = name;
20                         for ( var i = 0, l = this.length; i < l; i++ ) {
21                                 elem = this[i];
22                                 for ( name in options ) {
23                                         value = options[name];
24                                         if ( jQuery.isFunction(value) )
25                                                 value = value.call(elem,i);
26                                         jQuery.attr( elem, name, value );
27                                 }
28                         }
29                 }
30
31                 return this;
32         },
33
34         hasClass: function( selector ) {
35                 return !!selector && this.is( "." + selector );
36         },
37
38         val: function( value ) {
39                 if ( value === undefined ) {
40                         var elem = this[0];
41
42                         if ( elem ) {
43                                 if( jQuery.nodeName( elem, 'option' ) )
44                                         return (elem.attributes.value || {}).specified ? elem.value : elem.text;
45
46                                 // We need to handle select boxes special
47                                 if ( jQuery.nodeName( elem, "select" ) ) {
48                                         var index = elem.selectedIndex,
49                                                 values = [],
50                                                 options = elem.options,
51                                                 one = elem.type == "select-one";
52
53                                         // Nothing was selected
54                                         if ( index < 0 )
55                                                 return null;
56
57                                         // Loop through all the selected options
58                                         for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
59                                                 var option = options[ i ];
60
61                                                 if ( option.selected ) {
62                                                         // Get the specifc value for the option
63                                                         value = jQuery(option).val();
64
65                                                         // We don't need an array for one selects
66                                                         if ( one )
67                                                                 return value;
68
69                                                         // Multi-Selects return an array
70                                                         values.push( value );
71                                                 }
72                                         }
73
74                                         return values;
75                                 }
76
77                                 // Everything else, we just grab the value
78                                 return (elem.value || "").replace(/\r/g, "");
79
80                         }
81
82                         return undefined;
83                 }
84
85                 // Typecast once if the value is a number
86                 if ( typeof value === "number" )
87                         value += '';
88                         
89                 var val = value;
90
91                 return this.each(function(){
92                         if(jQuery.isFunction(value)) {
93                                 val = value.call(this);
94                                 // Typecast each time if the value is a Function and the appended
95                                 // value is therefore different each time.
96                                 if( typeof val === "number" ) val += '';
97                         }
98                         
99                         if ( this.nodeType != 1 )
100                                 return;
101
102                         if ( jQuery.isArray(val) && /radio|checkbox/.test( this.type ) )
103                                 this.checked = jQuery.inArray(this.value || this.name, val) >= 0;
104
105                         else if ( jQuery.nodeName( this, "select" ) ) {
106                                 var values = jQuery.makeArray(val);
107
108                                 jQuery( "option", this ).each(function(){
109                                         this.selected = jQuery.inArray( this.value || this.text, values ) >= 0;
110                                 });
111
112                                 if ( !values.length )
113                                         this.selectedIndex = -1;
114
115                         } else
116                                 this.value = val;
117                 });
118         }
119 });
120
121 jQuery.each({
122         removeAttr: function( name ) {
123                 jQuery.attr( this, name, "" );
124                 if (this.nodeType == 1)
125                         this.removeAttribute( name );
126         },
127
128         addClass: function( classNames ) {
129                 jQuery.className.add( this, classNames );
130         },
131
132         removeClass: function( classNames ) {
133                 jQuery.className.remove( this, classNames );
134         },
135
136         toggleClass: function( classNames, state ) {
137                 var type = typeof classNames;
138                 if ( type === "string" ) {
139                         // toggle individual class names
140                         var isBool = typeof state === "boolean", className, i = 0,
141                                 classNames = classNames.split( /\s+/ );
142                         while ( (className = classNames[ i++ ]) ) {
143                                 // check each className given, space seperated list
144                                 state = isBool ? state : !jQuery.className.has( this, className );
145                                 jQuery.className[ state ? "add" : "remove" ]( this, className );
146                         }
147                 } else if ( type === "undefined" || type === "boolean" ) {
148                         if ( this.className ) {
149                                 // store className if set
150                                 jQuery.data( this, "__className__", this.className );
151                         }
152                         // toggle whole className
153                         this.className = this.className || classNames === false ? "" : jQuery.data( this, "__className__" ) || "";
154                 }
155         }
156 }, function(name, fn){
157         jQuery.fn[ name ] = function(){
158                 return this.each( fn, arguments );
159         };
160 });
161
162 jQuery.extend({
163         className: {
164                 // internal only, use addClass("class")
165                 add: function( elem, classNames ) {
166                         jQuery.each((classNames || "").split(/\s+/), function(i, className){
167                                 if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
168                                         elem.className += (elem.className ? " " : "") + className;
169                         });
170                 },
171
172                 // internal only, use removeClass("class")
173                 remove: function( elem, classNames ) {
174                         if (elem.nodeType == 1)
175                                 elem.className = classNames !== undefined ?
176                                         jQuery.grep(elem.className.split(/\s+/), function(className){
177                                                 return !jQuery.className.has( classNames, className );
178                                         }).join(" ") :
179                                         "";
180                 },
181
182                 // internal only, use hasClass("class")
183                 has: function( elem, className ) {
184                         return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
185                 }
186         },
187
188         attr: function( elem, name, value ) {
189                 // don't set attributes on text and comment nodes
190                 if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
191                         return undefined;
192
193                 var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
194                         // Whether we are setting (or getting)
195                         set = value !== undefined;
196
197                 // Try to normalize/fix the name
198                 name = notxml && jQuery.props[ name ] || name;
199
200                 // Only do all the following if this is a node (faster for style)
201                 if ( elem.nodeType === 1 ) {
202
203                         // These attributes require special treatment
204                         var special = /href|src|style/.test( name );
205
206                         // Safari mis-reports the default selected property of a hidden option
207                         // Accessing the parent's selectedIndex property fixes it
208                         if ( name == "selected" && elem.parentNode )
209                                 elem.parentNode.selectedIndex;
210
211                         // If applicable, access the attribute via the DOM 0 way
212                         if ( name in elem && notxml && !special ) {
213                                 if ( set ){
214                                         // We can't allow the type property to be changed (since it causes problems in IE)
215                                         if ( name == "type" && /(button|input)/i.test(elem.nodeName) && elem.parentNode )
216                                                 throw "type property can't be changed";
217
218                                         elem[ name ] = value;
219                                 }
220
221                                 // browsers index elements by id/name on forms, give priority to attributes.
222                                 if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
223                                         return elem.getAttributeNode( name ).nodeValue;
224
225                                 // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
226                                 // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
227                                 if ( name == "tabIndex" ) {
228                                         var attributeNode = elem.getAttributeNode( "tabIndex" );
229                                         return attributeNode && attributeNode.specified
230                                                 ? attributeNode.value
231                                                 : /(button|input|object|select|textarea)/i.test(elem.nodeName)
232                                                         ? 0
233                                                         : /^(a|area)$/i.test(elem.nodeName) && elem.href
234                                                                 ? 0
235                                                                 : undefined;
236                                 }
237
238                                 return elem[ name ];
239                         }
240
241                         if ( !jQuery.support.style && notxml && name == "style" ) {
242                                 if ( set )
243                                         elem.style.cssText = "" + value;
244
245                                 return elem.style.cssText;
246                         }
247
248                         if ( set )
249                                 // convert the value to a string (all browsers do this but IE) see #1070
250                                 elem.setAttribute( name, "" + value );
251
252                         var attr = !jQuery.support.hrefNormalized && notxml && special
253                                         // Some attributes require a special call on IE
254                                         ? elem.getAttribute( name, 2 )
255                                         : elem.getAttribute( name );
256
257                         // Non-existent attributes return null, we normalize to undefined
258                         return attr === null ? undefined : attr;
259                 }
260
261                 // elem is actually elem.style ... set the style
262                 // Using attr for specific style information is now deprecated. Use style insead.
263                 return jQuery.style(elem, name, value);
264         }
265 });