When using a WebKit browser (Chrome or Safari), if I try to get the default value of a checkbox, it returns “”. However, the same javascript in Firefox or IE will return “on”.
So lets say I have this checkbox on a page:
<input type="checkbox" id="chkDefaultValue">
I use this javascript to return all “input” elements on a page
var elems = document.getElementsByTagName('input');
Then I go through a loop that gets the value like this
elems[i].getAttribute('value')
When elems[i] is that checkbox, in Chrome or Safari it returns “”, but Firefox or IE it returns “on”.
Is there any way to use Javascript to return the “on” value in Safari or Chrome? In Chrome I use a jquery call that uses .val() and that actually returns “on”, but I need a way to do this using Javascript in Safari.
Thanks!
EDIT:
I’m actually looking for the “value” attribute specifically since the “value” of a checkbox can be anything, like “cat” or “bike”.
Use checked instead to see if a checkbox or radio input is selected.
If what you really want to do is get the
valueattribute, and not see if the checkbox is selected, then you need to set a value for the checkbox first. If nothing is set then you gettingnullis the normal behavior.You can also replicate the Firefox and IE behavior by assigning
onyourself as a default value: