0

i have this jquery function:

function post_form(form_id) {
    $( form_id ).submit(function(e) {
        CheckRequired(e);
        var postData = $(this).serializeArray();
        var formURL = $(this).attr("action");
        LoadModalBody('<h2 align="center">Loading...</h3><p align="center"><i class="fa fa-refresh fa-spin fa-5x"></i></p>', 'Loading');
        $.ajax({
            url : '/section' + formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR) {
                LoadModal('/section' + formURL, 'Mileage');

                //$("body").html(data);
                //data: return data from server
            },
            error: function(jqXHR, textStatus, errorThrown) {
                //if fails
            }
        });
        e.preventDefault(); //STOP default action
        e.unbind(); //unbind. to stop multiple form submit.
    });
}

i want to call it in a HTML form submit button

i know i can use onClick="post_form(); but how do i put the form id in the call, i think using this would be the submit button and not the form?

2 Answers 2

2

This enought:

$('#form-id').submit(function(e){
  // code for validate or ither staff
});

Just remove first and last line of code in your example.

Sign up to request clarification or add additional context in comments.

2 Comments

if i call the function inside this, could i use $(this); to get the ID of the form?
Yes, you can use $(this).attr('id') for getting ID of form tag.
1

Normally you put this code at the top of the page and attribute it directly like this:

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script>
$(function(){
    $('#my-form').submit(function(e) {
        ...
    });
});
</script>
</head>
<body>
    <form id="my-form">
        ...
        <input type="submit" value="Click me to submit form" />
    </form>
</body>
</html>

20 Comments

can i use $(this); inside the .submit when calling the function ?
Yes. Inside the function $(this) will be the form wrapped in jQuery.
so i could use $('#my-form').submit(function(e) { form_post($(this)); });
oh you wouldn't have to call form_post anymore. Instead you're just telling the form what to do on submission.
but i want to run this function to post the form
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.