JavaScript - OnSubmit form works, but the action does not

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

It 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 does not work ( this.city.value is considered 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 can onsubmit get this.city.value , but the action cannot?

+4
source share
3 answers

The form action tag does not reference anything with this

Use absolute location instead

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

Change Thanks to Christoph's comment below, I realized my enormous oversight. Here is the final decision with his proposal.

 <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 paying attention to me in my previous answers.

+4
source

HTML forms are used to send data back to a script on the server to process the data. When the form is submitted, the data in the form fields is transmitted to the server in the form of name-value pairs. Server-side scripts that can be written in several different languages ​​are used to process incoming data and return a new HTML page to the browser. The page returned to the browser can be any of the “Thank you for registering” messages or a list of search results generated from the database query.

since the form is designed to send data to another file on the server. in action, we can only specify the path along which we need to send data. so you cannot get the values ​​that the form has.

0
source

Source: https://habr.com/ru/post/1286161/


All Articles