简体   繁体   中英

Submit a form using onclick event, but only allow once

I am both setting a form's action and submitting the form via the onclick event of a div:

<div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()">
<span class="action_button_label">Save</span>
</div>

This works fine, but I'm wanting to use some code that conditionally checks for the 'Save' in the action_label_button, and only lets the submit() fire once. I'm trying to prevent multiple saves (which is yielding duplicate data in my app) from occurring.

// disable save buttons onclick (prevent multiple clicks of save buttons)

$('.action_button_label').one('click', function() {
    // if the button is a save button
    if($(this).html().indexOf('Save') != -1) {
        // submit the parent form
            $(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
            $(this).parents('form').submit();
    }
});

$('form').bind('submit', function() {
    $(this).find('action_button').attr('onclick', '');
});

This code doesn't seem to work as I expected. I'm afraid I'm a bit out of my depth here, any pointers would be great.

Try replacing

$(this).find('action_button').attr('onclick', '');

with

$(this).find('.action_button').attr('onclick', '');

You should always handle multiple submits server side to ENSURE you don't get them. However you can hide the button-label to assist with this client side.

$('.action_button_label').one('click', function() {
    // if the button is a save button
    if($(this).html().indexOf('Save') != -1) {
        // submit the parent form
            $('.action_button_label').hide(); //ADD THIS
            $(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
            $(this).parents('form').submit();
    }
});

$('form').bind('submit', function() {
    $(this).find('action_button').attr('onclick', '');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM