Alert for unsaved changes in form

前端 未结 7 1912
谎友^
谎友^ 2020-11-30 18:47

I want to write Jquery code in master file, so that if there if user changes page and there is any unsaved changes user should get alert. I got one answer from this: link

7条回答
  •  情书的邮戳
    2020-11-30 19:14

    This is really just a different version of @AlphaMale's answer but improved in a few ways:

    # Message displayed to user. Depending on browser and if it is a turbolink,
    # regular link or user-driven navigation this may or may not display.
    msg = "This page is asking you to confirm that you want to leave - data you have entered may not be saved."
    
    # Default state
    unsaved = false
    
    # Mark the page as having unsaved content
    $(document).on 'change', 'form[method=post]:not([data-remote]) :input', -> unsaved = true
    
    # A new page was loaded via Turbolinks, reset state
    $(document).on 'page:change', -> setTimeout (-> unsaved = false), 10
    
    # The user submitted the form (to save) so no need to ask them.
    $(document).on 'submit', 'form[method=post]', ->
      unsaved = false
      return
    
    # Confirm with user if they try to go elsewhere
    $(window).bind 'beforeunload', -> return msg if unsaved
    
    # If page about to change via Turbolinks also confirm with user
    $(document).on 'page:before-change', (event) ->
      event.preventDefault() if unsaved && !confirm msg
    

    This is better in the following ways:

    • It is coffeescript which IMHO automatically makes it better. :)
    • It is entirely based on event bubbling so dynamic content is automatically handled (@AlphaMale's update also has this).
    • It only operates on POST forms as GET forms do not have data we typically want to avoid loosing (i.e. GET forms tend to be search boxes and filtering criteria).
    • It doesn't need to be bound to a specific button for carrying out the save. Anytime the form is submitted we assume that submission is saving.
    • It is Turbolinks compatible. If you don't need that just drop the two page: event bindings.
    • It is designed so that you can just include it with the rest of your JS and your entire site will be protected.

提交回复
热议问题