Getting Check box value from form on Safari

Some time ago jj posted this as a means of discovering what was on a form and getting it back to a script:

set js to "document.forms[0].elements[2].value"
tell application "Safari" to set Element2 to (do JavaScript js in document 1)
-- > returns the contents of that element whether it's a menu pick or a text box

If the element happens to be a checkbox, radio button or regular button, it just returns the value of the object. For a button, that’s the word on the button. In the case of a check box it’s the value assigned in a statement like this:

<p><input name="myCheckBox" type="checkbox" value="Check Here" unchecked> Text next to it</p>

My question: How do I find out if it’s checked or not from an AppleScript and return that to the AS?

[I’ve forgotten all the JavaScript I learned painfully 4 years ago - haven’t used it since]

Try something like this:

set js to "document.forms[0].elements[0].checked"
tell application "Safari" to set Element2 to (do JavaScript js in document 1)
--> "true" or "false" (Unicode text, not boolean)

Note that the index (“[0]” in my test file) for the various objects can vary from page to page. The important part is the “checked” property.

Side note: “unchecked” is not an attribute. If you want a checkbox checked by default, you can supply the “checked” attribute. Any other text is likely discarded by the user agent.

Coming back to AS. you can check if a checkbox has the “checked” attribute by using something like this:

set js to "document.forms[0].elements[0].defaultChecked"
tell application "Safari" to set Element2 to (do JavaScript js in document 1)
--> "true" or "false" (Unicode text, not boolean)

Thank you, thank you, Bruce;

You have saved me a ton of scrounging around in one easy lesson.

A