jquery Gets the check state of a checkbox
$ (' #checkboxID '). attr (' checked ');
found that the above code, regardless of whether the input checkbox is selected or unchecked, whether IE or chrome, the return results are undefinded;
Check found: jquery1.6 version of this modification, the checked property is initialized at the time of page initialization, and will not change with the state. That is, the checkbox is checked when the page is loaded, always returns checked, and if it is not selected at first, returns undefinded forever.
In jquery 1.6 and after, a new method prop () is added, the attr method is used to obtain the attribute, and the prop method is used to obtain the attribute. Use the Prop method when encountering properties that you want to get or set checked,selected,readonly and disabled.
Official explanation prop (): Gets the property value of the first element in a matching element set.
We all know that some browsers just write disabled,checked can be, and some to write disabled = "disabled", checked= "checked", such as with attr ("checked") The Checked property of the checkbox can be obtained when the value is selected, the value is "checked", but the get value is undefined.
JQ provides a new method of "prop" to get these properties, which is to solve this problem, we used attr to get the checked property when we return "checked" and "", and now use the Prop method to get the property is unified return True and false.
So, when to use attr (), when to use Prop ()?
1. Add property name This property will take effect should use Prop ();
2. There are true,false two attributes using prop ();
3. The other uses attr ();
The following are the official recommendations for the use of attr (), prop ():
Attribute/property |
. attr () |
. Prop () |
AccessKey |
√ |
|
Align |
√ |
|
Async |
√ |
√ |
Autofocus |
√ |
√ |
Checked |
√ |
√ |
Class |
√ |
|
Contenteditable |
√ |
|
Draggable |
√ |
|
Href |
√ |
|
Id |
√ |
|
Label |
√ |
|
Location (i.e. window.location) |
√ |
√ |
Multiple |
√ |
√ |
ReadOnly |
√ |
√ |
Rel |
√ |
|
Selected |
√ |
√ |
Src |
√ |
|
TabIndex |
√ |
|
Title |
√ |
|
Type |
√ |
|
Width (if needed over. Width ()) |
√ |
|
JS checkbox Check Status