Properties
Besides attributes, there are also element properties — these include selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected. Well, the list isn't that long, you can memorize it. To work with properties we use methods from the prop() family:
get the property value
set the property value
set multiple values
using a callback function
index is the element's position in the selection
value is the current property value
remove a property (most likely, you'll never need this)
Let's see an example:
See how the system works without our interference — click the checkbox, the dropdown, try submitting the form.
Now let's run a series of experiments (don't forget to refresh the page):
Check the checkbox using the
attr()method:Now uncheck it with the mouse — the
attr()value remained unchanged, while theprop()value changedTry checking it again using the
attr()method
Next experiment:
Check the checkbox with the mouse
Uncheck it — the
attr()value doesn't changeTry setting the value by calling:
What's interesting in this experiment is this: calling attr("checked", "checked") doesn't work after the user has changed the checkbox state
And one more experiment with the second checkbox:
Remove the check:
Set the check:
Remove the check again using
attr()Repeat until you drop
If it works — don't touch it, you'll break everything with the mouse :)
Compare this with the behavior of prop():
Remove the check:
Set the check:
You can click the checkbox with the mouse and repeat the steps above in any order — everything will work like clockwork
I hope I've made it clear enough when to use
attr()and when to useprop()
That's not all — we still have the disabled property! But don't worry, its behavior is more predictable since the user can't interfere with its state:
Enable the radio button:
Disable it:
Repeat
Same behavior when using prop():
Enable:
Disable:
Repeat
Well, you could use
attr(), but no!
Last updated