JavaScript - Form OnSubmit works but Action doesn't

Zoowealander picture Zoowealander · Jun 13, 2009 · Viewed 30.3k times · Source

On my FORM, for some reason, I can get my form input variable via onsubmit but not using action.

This works:

<form onsubmit="javascript:myFunc(this.city.value);">
    <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p>
</form>

This doesn't work (this.city.value is found to be null)

<form action="javascript:myFunc(this.city.value);">
    <p><input type="text" id="city-field" name="city" onfocus="this.select();" /> <input type="submit" value="Find" /></p>
</form>

Why is it that onsubmit can get the this.city.value but the action event cannot?

Answer

Ian Elliott picture Ian Elliott · Jun 13, 2009

The form action tag doesn't reference anything with this

Instead, use an absolute location

action="javascript:myFnc(document.getElementById('city-field').value)"