如果文本区域不为空,则停止用户操作

时间:2014-10-14 06:59:29

标签: jquery jquery-ui

我想要一个jquery代码来检查文本区域是否为空?

如果它不为空并且用户尝试刷新页面或注销用户应该出现一个对话框,要求确认退出

的Javascript

     <script type = "text/javascript" >
    $(document).ready(function () {
        var ta = $('#text_area').val();
        if (ta != "") {

            $("#dialog-confirm").html("You have unsaved data on this page. Do you wish to ?");
            $('#dialog-confirm').attr('title', 'Confirm Exit').dialog({
                buttons : {
                    'Leave this page' : function () {
                        $(this).dialog('close');

                        $("html,body").css("overflow", "auto");

                    },
                    'Stay on this page' : function () {
                        $(this).dialog('close');
                        $("html,body").css("overflow", "auto");
                    }

                },
                closeOnEscape : false,
                draggable : false,
                resizable : false,
                show : 'fade',
                modal : true,
                width : '500px',
                maxHeight : 500,
                open : function (event, ui) {

                    $(this).parent().children().children(".ui-dialog-titlebar-close").click(function () {
                        $("html,body").css("overflow", "auto");
                    });
                }
            });
        }
    });

</script>

HTML

<textarea id = "text_area"> </textarea>
<div id="dialog-confirm"></div>

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

你应该听window.onbeforeunload事件。例如:

<强>更新 这是一个更精细的例子,作为一个html文件:(在MDN阅读更多内容)

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script type="text/javascript">
      window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = "You have made changes to textarea";
        if ($("#myTextArea").val()) {
            (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
            return confirmationMessage;                                //Webkit, Safari, Chrome etc.
        }

      });
    </script>
  </head>
  <body>
    <textarea name="" id="myTextArea" cols="30" rows="10"></textarea>
 </body>
</html>