JavaScript - Form OnSubmit works but Action doesn't

30,344

Solution 1

The form action tag doesn't reference anything with this

Instead, use an absolute location

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

Solution 2

Edit: Thanks to Christoph's comment, below, I realized my huge oversight. Here is the final solution with his suggestion implemented.

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

This should do what you need. I apologize for not giving you my full attention in my previous responses.

Share:
30,344
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • Admin
    Admin almost 15 years
    That causes the page to reload - I don't need the page to reload.
  • Christoph
    Christoph almost 15 years
    you can prevent the default action by returning false from the event handler, ie onsubmit="myFunc(this.city.value); return false;"
  • Admin
    Admin almost 15 years
    I tried it and OnClick event doesn't work. Would you need to use the OnSubmit event (which is only present if within a FORM)?