양식에 저장되지 않은 변경 사항에 대한 경고
마스터 파일에 Jquery 코드를 작성하여 사용자가 페이지를 변경하고 저장되지 않은 변경 사항이 있으면 경고를 받아야합니다. 나는 이것에서 하나의 대답을 얻었다 : 링크
그러나 대부분의 솔루션에서는 모든 페이지에 코드를 작성해야합니다. 모두가 자신의 모듈에 작성하는 것을 걱정할 필요가 없도록 한 곳에만 작성하고 싶습니다. 내 코드는 다음과 같습니다.
<script type="text/javascript">
var isChange;
$(document).ready(function () {
$("input[type='text']").change(function () {
isChange = true;
})
});
$(window).unload(function () {
if (isChange) {
alert('Handler for .unload() called.');
}
});
</script>
하지만 텍스트 상자를 변경할 때마다 .change () 이벤트가 발생하지 않습니다.
코드에서 무엇이 잘못 될 수 있습니까?
편집 : .change ()를 .click으로 변경하면 해고됩니다. jquery 1.4.1을 사용하고 있습니다. jquery 버전 때문에 change ()가 작동하지 않습니까?
이것이 내가 사용하는 것입니다.이 모든 코드를 별도의 JS 파일에 넣고 헤더 파일에로드하면 이것을 반복해서 복사 할 필요가 없습니다.
var unsaved = false;
$(":input").change(function(){ //triggers change in all input fields including text type
unsaved = true;
});
function unloadPage(){
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
}
window.onbeforeunload = unloadPage;
$에 대한 편집을 찾을 수 없음 :
이 오류는 다음 세 가지 중 하나에 의해서만 발생할 수 있습니다.
- 자바 스크립트 파일이 페이지에 제대로로드되지 않았습니다.
- 잘못된 버전의 jQuery가 있습니다. 누군가 코어 파일을 편집했거나 플러그인이 $ 변수를 덮어 썼기 때문에 이런 일이 발생할 수 있습니다.
- 페이지가 완전히로드되기 전과 jQuery가 완전히로드되기 전에 JavaScript가 실행 중입니다.
모든 JS 코드가 다음 위치에 있는지 확인하십시오.
$(document).ready(function () {
//place above code here
});
저장 / 보내기 / 제출 단추 예외 편집
$('#save').click(function() {
unsaved = false;
});
동적 입력으로 작업하도록 편집
// Another way to bind the event
$(window).bind('beforeunload', function() {
if(unsaved){
return "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
}
});
// Monitor dynamic inputs
$(document).on('change', ':input', function(){ //triggers change in all input fields including text type
unsaved = true;
});
alert_unsaved_changes.js 파일에 위 코드를 추가하십시오.
도움이 되었기를 바랍니다.
다음 형식의 직렬화를 사용하는 버전 :
DOM이 준비되면 다음 코드를 실행하십시오.
// Store form state at page load
var initial_form_state = $('#myform').serialize();
// Store form state after form submit
$('#myform').submit(function(){
initial_form_state = $('#myform').serialize();
});
// Check form changes before leaving the page and warn user if needed
$(window).bind('beforeunload', function(e) {
var form_state = $('#myform').serialize();
if(initial_form_state != form_state){
var message = "You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?";
e.returnValue = message; // Cross-browser compatibility (src: MDN)
return message;
}
});
사용자가 필드를 변경 한 다음 수동으로 롤백하면 경고가 표시되지 않습니다.
사용자가 입력 된 모든 단일 문자가 아닌 입력에서 흐려지면 change 이벤트가 시작됩니다.
If you need it to be called every time something is changed (even if focus is still in that input field) you would have to rely on combination of keyup and bunch of events to keep track of pasting/cuting using mouse only.
P.S. I hope you're aware that your approach to detecting changes isn't the best one? If user input some text, leaves the field and then reverts the changes the script would still alert him about modified text.
you should register events for not only inputs but also textareas, if you mean textarea with text box. You can use keyup for isChange, so that you don't wait for user to blur from this area.
$("input[type='text'], textarea").keyup(function () {
isChange = true;
})
Why not simply bind the event to the change
callback?
$(":input").change(function()
{
$(window).unbind('unload').bind('unload',function()
{
alert('unsaved changes on the page');
});
});
As an added bonus, you can use confirm
and select the last element that triggered the change event:
$(":input").change(function()
{
$(window).unbind('unload').bind('unload',(function(elem)
{//elem holds reference to changed element
return function(e)
{//get the event object:
e = e || window.event;
if (confirm('unsaved changes on the page\nDo you wish to save them first?'))
{
elem.focus();//select element
return false;//in jQuery this stops the event from completeing
}
}
}($(this)));//passed elem here, I passed it as a jQ object, so elem.focus() works
//pass it as <this>, then you'll have to do $(elem).focus(); or write pure JS
});
If you have some save button, make sure that that unbinds the unload event, though:
$('#save').click(function()
{
$(window).unbind('unload');
//rest of your code here
});
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.
I use $('form').change
etc. function to set a dirty bit variable. Not suitable to catch all changes (as per previous answers), but catches all that I'm interested in, in my app.
참고URL : https://stackoverflow.com/questions/11844256/alert-for-unsaved-changes-in-form
'Nice programing' 카테고리의 다른 글
서로 다른 데이터 프레임의 두 플롯을 결합하는 ggplot (0) | 2020.11.27 |
---|---|
jQuery는 postmessage 이벤트를 지원하지 않습니까? (0) | 2020.11.27 |
C # 스위치와 함께 열거 형을 사용하는 방법 (0) | 2020.11.27 |
JTable, 사용자 열 드래그 비활성화 (0) | 2020.11.27 |
pkl 파일의 압축을 푸는 방법은 무엇입니까? (0) | 2020.11.27 |