AppleScript set value to web form input field via JavaScript

I am trying to force a registration via Applescript. There is a form field requiring an email. I am successfully adding the email to the form field but it is still not recognized as it’s “value”. When I inspect the element the value is not set. But if I click in the form field and add a space then the value is recognized. I am not sure how to get around this. I have tried to use focus(), click(), multiple keystrokes and no matter what I do the value is never set using Applescript.



set email to the text returned of (display dialog "Enter in Your Email to Validate Your Purchase:" default answer "")

tell application "Safari"
        make new document at end of documents
        set URL of document 1 to "https://myurl.com"
        tell application "System Events" 

            set theScript to "document.getElementById('email').value= '" & email & "';"

        end tell

        delay 3 

        do JavaScript theScript in document 1

end tell


I got it working:


tell application "Safari"
make new document at end of documents
set URL of document 1 to "https://www.myurl.com"

        delay 1
        do JavaScript "document.getElementById('email').focus();" in document 1
        delay 1
        do JavaScript "document.getElementById('email').select();" in document 1
        delay 1
        do JavaScript "document.getElementById('email').value = '" & email & "';" in document 1
        delay 1
        tell application "System Events"
            keystroke space
        end tell
end tell