Jquery function BEFORE form submission

2019-01-22 10:41发布

I am trying to fire a function using Jquery when the form submit button is clicked, but the function needs to fire BEFORE the form is actually submitted.

I am trying to copy some div tag attributes into hidden text fields upon submission, and then submit the form.

I have managed to get this to work using the mouseover function (when the submit button is hovered over) but this will not work on mobile devices using touch.

$("#create-card-process.design #submit").on("mouseover", function () {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

I have played around with the .submit function, but the values are not saved within the fields as the function fires when the form is submitted and not before.

Many thanks

5条回答
Emotional °昔
2楼-- · 2019-01-22 11:07

You can use the onsubmit function.

If you return false the form won't get submitted. Read up about it here.

$('#myform').submit(function() {
  // your code here
});
查看更多
爷的心禁止访问
3楼-- · 2019-01-22 11:12
$('#myform').submit(function() {
  // your code here
})

The above is NOT working in Firefox. The form will just simply submit without running your code first. Also the similar issues are mentioned elsewhere... such as this question. The work around will be

$('#myform').submit(function(event) {

 event.preventDefault(); //this will prevent the default submit

  // your code here (But not asynchronous code such as Ajax because it does not wait for response and move to next line.)

 $(this).unbind('submit').submit(); // continue the submit unbind preventDefault
})
查看更多
姐就是有狂的资本
4楼-- · 2019-01-22 11:20

You can use some div or span instead of button and then on click call some function which submits form at he end.

<form id="my_form">
   <span onclick="submit()">submit</span>
</form>

<script>
   function submit()
   {   
       //do something
       $("#my_form").submit();
   }
</script>
查看更多
趁早两清
5楼-- · 2019-01-22 11:28

Aghhh... i was missing some code when i first tried the .submit function.....

This works:

$('#create-card-process.design').submit(function() {
var textStyleCSS = $("#cover-text").attr('style');
var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
$("#cover_text_css").val(textStyleCSS);
$("#cover_text_background_css").val(textbackgroundCSS);
});

Thanks for all the comments.

查看更多
倾城 Initia
6楼-- · 2019-01-22 11:28

Just because I made this mistake every time when using the submit function.

This is the full code you need:

Add the id "yourid" to the HTML form tag.

<form id="yourid" action='XXX' name='form' method='POST' accept-charset='UTF-8' enctype='multipart/form-data'>

the jQuery code:

$('#yourid').submit(function() {
  // do something
});
查看更多
登录 后发表回答