How can I prevent a double submit with jQuery or Javascript?

前端 未结 10 1303
终归单人心
终归单人心 2020-12-08 22:44

I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.

I googled and googled and found a few scripts,

10条回答
  •  南笙
    南笙 (楼主)
    2020-12-08 22:51

    Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:

    • button elements
    • img elements
    • javascripts
    • pressing 'enter' while on some text field

    Using jQuery data container would be my choice. Here's an example:

    $('#someForm').submit(function(){
        $this = $(this);
    
        /** prevent double posting */
        if ($this.data().isSubmitted) {
            return false;
        }
    
        /** do some processing */
    
        /** mark the form as processed, so we will not process it again */
        $this.data().isSubmitted = true;
    
        return true;
    });
    

提交回复
热议问题