Html submit action javascript function

Form Submit Execute JavaScript Best Practice? [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

I would like to run a JavaScript function when a form is submitted. The issue is that, when the form is submitted, the page is reloaded and the form values are appended to the URL as GET parameters. I would like it to stay on the current page and only run the JavaScript function. I was wondering what the best practice (or what you do) to avoid having the page reload and parameters be sent.

To avoid parameters be sent? 😮 Don’t you mean, to avoid the parameter to show up in browser address bar? Basicaly using POST instead of GET would also solve this (useful to know if you’d like to support JS-disabled clients as well, such as several mobile phone users).

3 Answers 3

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event’s preventDefault method to disable the form submission.

This works, but it’s best not to litter your HTML with JavaScript, just as you shouldn’t write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

Читайте также:  Нужны внутренние классы java

While browsers may be able to deal with it correctly I’d like to suggest closing the tag for better consistency, e.g.

If you’d like to use vanilla Javascript (in my opinion you should always try to): document.getElementsByClassName(‘.my-form’)[0].addEventListener(‘submit’,function()< alert('Form submitted'); return false; >);

@moteutch and how would you pass the values of potential form input fields to the function? should it just find them in the document or can i somehow pass them as function parameters?

I know it’s a little late for this. But I always thought that the best way to create event listeners is directly from JavaScript. Kind of like not applying inline CSS styles.

function validate() < //do stuff >function init() < document.getElementById('form').onsubmit = validate; >window.onload = init; 

That way you don’t have a bunch of event listeners throughout your HTML.

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.17.43537

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Setting the Form Action with a JavaScript Function

In an HTML form, the action attribute is used to indicate where the form’s data is sent to when it is submitted. The value of this can be set when the form is created, but at times you might want to set it dynamically. In this tutorial, we’ll look at ways in which a form’s action attribute can be set dynamically by JavaScript.

To get started, create an HTML file and paste the following form to its body.

form onsubmit="return setAction(this)">  div>  label>Name:label>  input id="name" name="name" type="text">  div>  div>  label>Email:label>  input id="email" name="email" type="email">  div>  div>  input id="submit" type="submit">  div>  form> 

The above markup is for a simple form with two fields and a submit button. We’ve set an onsubmit listener which will be called when the form is submitted. This will, in turn, make a call to the setAction() function that we’ll soon define. In the function call, the form passes a reference to itself ( this ).

Add the following CSS styling:

form label   display: inline-block;  width: 100px; >  form div   margin-bottom: 10px; > 

Add the following JavaScript to the file.

function setAction(form)   form.action = "register.html";  alert(form.action);  return false; > 

In the above, we assign the passed in form reference to the form variable. Then we set its action attribute with form.action = «register.html» . This will result in the form’s action getting set to BASE_URL/register.html . The BASE_URL will be the URL the HTML file is running on. To test that the action was set, we display its value in an alert box. The function then returns false to prevent the form from getting submitted. This is included in the demo code since the /register.html page doesn’t exist, but in a real application, you would want the form to be submitted.

Next, we’ll look at another example where the form action will be set depending on the button used to submit the form.

You can add the following to the HTML file.

form name="user_form">  div>  label>Email:label>  input id="user_email" name="user_email" type="email">  div>  div>  label>Password:label>  input id="user_password" name="user_password" type="password">  div>  div>  input id="login" type="submit" value="Login" onclick="return loginUser()">  div>  div>  input id="register" type="submit" value="Register" onclick="return registerUser()">  div>  form> 

The above form has two buttons that have been set up with onclick listeners. Each listener makes a call to a different button when clicked.

Add the following JavaScript to the file.

function loginUser()   document.user_form.action = "login.html";  alert(document.user_form.action);  return false; >  function registerUser()   document.user_form.action = "register.html";  alert(document.user_form.action);  return false; > 

loginUser() gets called when the Login button is clicked. The function sets /login.html as the value of the form’s action attribute. In this example, we get a reference to the form with document.user_form . For this to work, the name attribute of the form has to be set to user_form . After setting the action attribute, we alert the value and return false thus preventing form submission.

registerUser is called when the Register button is clicked and it sets ./register.html as the form’s action.

See the code in action below:

Источник

How can I set the form action through JavaScript?

I have an HTML form whose action should be set dynamically through JavaScript. How do I do it? Here is what I am trying to achieve:

8 Answers 8

You cannot invoke JavaScript functions in standard HTML attributes other than onXXX . Just assign it during window onload.

 window.onload = function() < document.myform.action = get_action(); >function get_action() 
.

You see that I’ve given the form a name , so that it’s easily accessible in document .

Alternatively, you can also do it during submit event:

Although, depending on markup this may not validate, the ‘name’ attribute is not a valid attribute in XML, its better to use an ID and use the getElementById

@Rabbott: It’s HTML, not XML. XHTML is only interesting for server-side HTML-autogenerators like componentbased MVC frameworks.

document.getElementById('form_id').action; //Will retrieve it document.getElementById('form_id').action = "script.php"; //Will set it 
$("#form_id").attr("action"); //Will retrieve it $("#form_id").attr("action", "/script.php"); //Will set it 

Hi, I think for plain JavaScript line 2: document.getElementById(‘form_id’).action = «script.php» will retrieve it

It was a nice option, I used the Plain Javascript Option. I worked in the desktop view. But not getting that worked with mobile browsers

Very easy solution with jQuery:

$('#myFormId').attr('action', 'myNewActionTarget.html'); 

Actually, when we want this, we want to change the action depending on which submit button we press.

Here you do not need even assign name or id to the form. Just use the form property of the clicked element:

Change the action URL of a form:

  

. assuming it is the first form on the page.

this might work, but i am still trying to make it work by getting the action string from a function. is there no way to do it like that?

You can write it in an onsubmit event handler to make sure it always gets just just before submission. However, in general trying to change a form action from script is a code smell; unless you don’t control the server side, it’s usually better to make the form accept two+ different submission modes.

Источник

Calling JS Function on Form Submit

I have created a JS function which executes fine when it’s included an the ‘onclick’ action of standard HTML link tag as follows:

However where I really want to use this function is on the ‘onsubmit’ action of a form but when I include it as follows the function no longer seems to be executing:

What the ‘fb_CheckPermission()’ JS function basically does is use Facebook Connect to check to make sure the user has granted us a specific permission and if not it tells Facebook Connect to prompt the user to grant the permission. Here is the code for the JS function:

1. function fb_checkPermission(permission) < 2. FB.ensureInit(function() < 3. FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) < 4. if(!hasPermissions)< 5. FB.Connect.showPermissionDialog(permission,function (status)< 6. if(!status) < 7. if(permission == 'offline_access') < 8. // save session 9. >10. > 11. >); 12. > 13. >); 14. >); 15.> 
Line 2: Make sure Facebook Connect JS library is loaded Line 3: Checks to see if the current Facebook Connect user has granted a specific permission Line 5: If the permission hasn't been granted then prompt the user with the permission dialog Line 7: In the case of the 'offline_access' permission save the session key once granted 

The user experience I’m trying to achieve is that when a user submits the form I’ll check to see if they have granted a specific permission and if not prompt them for the permission before submitting the form. If the user has already granted the permission the form should just submit. For those users who are prompted the form should submit after they either choose to grant the permission or if the deny the request which I believe the fb_checkPermission() JS function is handling correctly right now. What I’m not sure is if there is some kind of JavaScript issue with how this works on form submission. As I mentioned, this JS function works perfectly as an onclick action but fails as an onsubmit action so I’m pretty sure that this has something to do with how JavaScript treats onsubmit actions. I’m stuck so I really appreciate your help in figuring out how to change the JS function to produce my desired user experience. Thanks in advance for your help!

Источник

Оцените статью