views:

2461

answers:

3

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?

A: 

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.

bchang
That causes the page to reload - I don't need the page to reload.
I noticed it right after I posted my answer, but I've since updated to include an example that does not reload.
bchang
you can prevent the default action by returning `false` from the event handler, ie `onsubmit="myFunc(this.city.value); return false;"`
Christoph
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)?
+1  A: 

The form action tag doesn't reference anything with this

Instead, use an absolute location

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

HTML forms are used for submitting data back to a script on the server for data processing. When a form is submitted, the data in the form fields is passed to the server in the form of name-value pairs. Server-side scripts, which can be written in several different languages, are used to process the incoming data and return a new HTML page to the browser. The page returned to the browser could be anything from a "Thank you for registering" message or a list of search results generated from a database query.

since form is for sending data to another file on the server. in action we can only specify the path to which we need to send the data. so there you cant get the values which the form is having.

tummy.developer