Search code examples
jqueryformsjspwarningsonbeforeunload

How to use AreYouSure correctly?


Update

I'm trying to warn user before leaving web page with unsaved changes. I saw that it should be easy with the jquery plugin AreYouSure.js

But, as its not working for me yet, I'd like to know what I've done wrong:

$(function() {
  $('#SummaryTableForm').areYouSure({
    message: 'It looks like you have been editing something. ' +
      'If you leave before saving, your changes will be lost.'
  });
});

function RemoveTableRowfunctionOfSummary(e) {
  $(e).parent().parent().remove();

}
<spring:url value="/resources/scripts/SummaryTableScript.js" var="SummaryTableScript" />
<script src="${SummaryTableScript}"></script>
<spring:url value="/resources/scripts/jquery.are-you-sure.js" var="AYS" />
<script src="${AYS}"></script>
<spring:url value="/resources/scripts/ays-beforeunload-shim.js" var="AYSbeforeunload" />
<script src="${AYSbeforeunload}"></script>
<form id="SummaryTableForm" name="SummaryTableForm" method="post" action="">
  <h1>
    <label id="SummaryTableHeadLineLabel">Summary</label>
  </h1>
  <div id="SumHeaderButton">

    <input type="submit" id="SumSaveBtn" value='Save'></input>
    <input type="button" id="SumCancelBtn" value='Cancel'></input>
  </div>
  <div id="SumActionButtons">
    <input type="button" id="SumDeleteBtn" value='Delete' />
    <input type="button" id="SumAddBtn" value='Add'></input>
  </div>
  <div id="SumTableDiv">
    <table id="SumTable">
      <thead>
        <tr>
          <td><label id="SummaryTableSelect">Select</label></td>
          <td><label id="SummaryTableActvate">Activate</label></td>
          <td><label id="SummaryTableId">ID</label></td>
          <td><label id="SummaryTableEdit">Edit</label></td>
          <td><label id="SummaryTableDelete">Delete</label></td>
        </tr>
        <tr>
          <td>
            <select id="SummaryTableSelectAll" onchange="changeSelectAll()">
              <option value="-1"></option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select>
          </td>
          <td>
            <select id="SummaryTableSelectActivate" onchange="changeActivation()">
              <option value="-1"></option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select>
          </td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      </thead>
      <tbody id="sumTbody">
        <tr>
          <td><input type="checkbox"></td>
          <td><input type="checkbox"></td>
          <td>1</td>
          <td><input type="button" id="SumDeleteBtn" value='Edit' /></td>
          <td><input type="button" id="SumDeleteBtn" value='Delete' onclick="RemoveTableRowfunctionOfSummary(this)" /></td>
        </tr>
        <tr>
          <td><input type="checkbox"></td>
          <td><input type="checkbox" checked></td>
          <td>2</td>
          <td><input type="button" id="SumDeleteBtn" value='Edit' /></td>
          <td><input type="button" id="SumDeleteBtn" value='Delete' onclick="RemoveTableRowfunctionOfSummary(this)" /></td>
        </tr>
      </tbody>
    </table>
    <nav class="limit-per-page" aria-label="Page Navigation">
      <ul class="pagination">
      </ul>
      <ul class="limit-per-page">
        <li><a href="javascript:void(0)" onclick="changeTo10()">10
				</a></li>
        <li><a href="javascript:void(0)" onclick="changeTo50()">50
				</a></li>
        <li><a href="javascript:void(0)" onclick="changeTo100()">100
				</a></li>
      </ul>
    </nav>
  </div>

The table is filled with ajax in (I've inserted some example tbl), there I have delete buttons and checkboxes. I want to warn the user before he can click on an other menue-link or before he can close the page, IF he/she has changed the value of the checkbox or if he has deleted the item.

As I'had read before the Are-you-sure.js should be easily implemented with:

$('#SummaryTableForm').areYouSure(
  {
    message: 'It looks like you have been editing something. '
       + 'If you leave before saving, your changes will be lost.'
  }
);

But it's not working in my code.

Additional Code for the dynamic table

Servlet to load the table

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    String createTableRows = "";

    List<TableRowModel> tableRowModelList= GetExamnTable();
    int paramIndex = 0;

    for (TableRowModel item : tableRowModelList)
    {
        String checked="";
        if(item.getActive()) {
            checked="checked";
        }
        createTableRows += "<tr id=\"SelectTableRowNumber"+paramIndex+"\" class=\"table-row  found-row\">"
            + "<td>"
            + "<input type=\"checkbox\" id=\"SummaryTableSelect"+paramIndex+"\" class=\"sum-table-select\"/>"
            + "</td>"
            + "<td>"
            + "<input type=\"checkbox\" name=\"SummaryTableActvateCheckbox\" id=\"SummaryTableActvate"+paramIndex+"\" "+checked+"  class=\"sum-table-activate\"  onchange=\"setChangedFlag()\"/>"
            + "</td>"
            + "<td class=\"sum-table-id\">"
            + "<label id=\"SummaryTableId"+paramIndex+"\" >"+item.getId()+"</label>"
            + "</td>"
            + "<td>"
            + "<input type=\"button\" value=\""+Utilities.getGeneralResourceMessages("button.Edit")+"\" onclick=\"EditTableRowfunction(this)\""
            + "</td>"
            + "<td>"
            + "<input type=\"button\" name=\"SummaryTableDeleteRow\" value=\""+Utilities.getGeneralResourceMessages("button.Delete")+"\" onclick=\"RemoveTableRowfunctionOfSummary(this)\""
            + "</td></tr>";

        paramIndex++;
    }

    out.print("{");
    out.print("'summaryTable':'" + createTableRows + "'");
    out.print("}");
}

Ajax to load the table:

$(document).ready(function() {
 $("#SummaryTableSelectAll").val("-1");
 $("#SummaryTableSelectActivate").val("-1");
//On Page-Ready load Datatable
$(function() {
    $("#SumTable tbody > tr").remove();
    var url = "Summary";
    var form = $('#SummaryTableForm')[0];
    var data = new FormData(form);
    $.ajax({
            type : "POST",
            url : url,
            data : data,
            processData: false,
            success : function(msg) {
                var objJSON = eval("(function(){return " + msg+ ";})()");
                $("#SumTable  tbody").append(objJSON.summaryTable);
                limitPerPage=3;
                startingPage=1;
                nextPageBlock = blockLimit;
                setPagination(limitPerPage);
                }
    });
});
});

If I check or uncheck the checkbox with a name-attribute and than move to a different page, I'll not receive the Pop-Up.

Solution Summary

To receive the popup, once inputs have to have a name-Attribute. If there is some dynamically created code AYS has to rescann the form: $('#SummaryTableForm').trigger('rescan.areYouSure'); If buttons are clicked and the event should trigger the AYS-popup. Then, on button click, one has to add the class-attr dirty to the form. $('#SummaryTableForm').attr("class","dirty");


Solution

  • For the plugin to work you have to give name attributes to the form controls, since it's how it keeps track of changes.

    Since form fields are collected at areYouSure initialization you'll have to manually trigger a rescan of the form after adding new rows as part of your success callback:

    $('#SummaryTableForm').trigger('rescan.areYouSure');