开发者

recursion issue with preventDefault on form submit with jquery

开发者 https://www.devze.com 2023-03-03 19:24 出处:网络
I have a form that takes some inputs, everything there is peachy.From this form I want to take a input value and assign it to a hidden value via jquery.To do this I had written the following:

I have a form that takes some inputs, everything there is peachy. From this form I want to take a input value and assign it to a hidden value via jquery. To do this I had written the following:

<script type="text/javascript">
    jQuery(document).ready(function() {
        function preventDefault(e){
            e.preventDefault();
        }

        jQuery('#rsvp-form').bind('submit', preventDefault);
        jQuery('#rsvp-form').submit(function(e) {
            var emailvalue = jQuery('#personemail\\[0\\]').val();
            jQuery('#per开发者_运维问答son_email').val(emailvalue);
            alert(jQuery("#person_email").val());
            jQuery('#rsvp-form').unbind('submit', preventDefault);
            jQuery(this).trigger('submit');
        });
    });
</script>

I'm binding .preventDefault to the submit just fine along with changing my value without issue. The problem is submitting the form after changing the value. No matter what I've tried it ends in an endless loop. If I remove the trigger or a .submit() or something along those lines and just leave it with the unbind, nothing happens. Kind of stumped at this point.


You shouldn't need any of that. If you want to set that value before the form submits you can do so easily like this:

jQuery(function() {
    jQuery('#rsvp-form').submit(function(e) {
        var emailvalue = jQuery('#personemail\\[0\\]').val();
        jQuery('#person_email').val(emailvalue);
    });
});


You need to call the native submit method, rather than triggering the jQuery event.

jQuery('#rsvp-form').submit(function(e) {
    var emailvalue = jQuery('#personemail\\[0\\]').val();
    jQuery('#person_email').val(emailvalue);
    alert(jQuery("#person_email").val());
    jQuery('#rsvp-form').unbind('submit', preventDefault);
    this.submit(); // <-- this line here
});
0

精彩评论

暂无评论...
验证码 换一张
取 消