javascripthtmljqueryjquery-dirtyforms

Check if a form is dirty and inform user before dynamically removing it


My page has a list of forms. Each form will be dynamically built by D3 when the user clicks on the form name in the list. Below is the code:

$(document).ready(function() {

  // display corresponding form for each click
  d3.selectAll(".form-name").on("click", function() {
    // check if the current form is dirty first
    var isDirty = $(document.querySelector('#main-part form')).dirtyForms('isDirty');

    if (isDirty) {
      console.log('form is dirty');
     
    	// display confirmation dialog
      

    } else {
      console.log('form is NOT dirty');
      buildForm(d3.select(this).attr('id'));
    }
  })
});

function buildForm(id) {
  var formId = "form_" + id;
  var myform = d3.select("#main-part")
    .select("form")
    .attr("id", formId);

  myform.selectAll("*").remove();
  myform.append("span").text("Feedback for " + formId);
  // Appending up and down vote radio button
  var radio_groups = myform
    .append('div')
    .attr('class', 'form-group');

  // Radio for upvote
  var radio_grp_chk = radio_groups
    .append('div')
    .attr('class', 'form-check form-check-inline upvote');
  radio_grp_chk
    .append('input')
    .attr('class', 'form-check-input')
    .attr('type', 'radio')
    .attr('name', 'voting-radio')
    .attr('value', 'thumbup')
    .attr('required', '');
  radio_grp_chk.append('span').text('Up');

  // Radio for downvote
  var radio_grp_chk2 = radio_groups
    .append('div')
    .attr('class', 'form-check form-check-inline downvote');
  radio_grp_chk2
    .append('input')
    .attr('class', 'form-check-input')
    .attr('type', 'radio')
    .attr('name', 'voting-radio')
    .attr('value', 'thumbdown')
    .attr('required', '');
  radio_grp_chk2.append('span').text('Down');

  // Appending feedback text area
  var text_group = myform.append('div').attr('class', 'form-group');
  text_group
    .append('label')
    .attr('for', 'feedback-txt')
    .text('Feedback');

  text_group
    .append('textarea')
    .attr('class', 'form-control feedback-text')
    .attr('id', 'feedback-text')
    .attr('placeholder', 'Enter...');

  // Submit button
  myform.append('button')
    .attr('type', 'submit')
    .attr('class', 'btn btn-primary rating-btn')
    .attr('id', 'submit-form')
    .text('Submit');

  // Initialize dirty form
  $("#" + formId).dirtyForms({
    dialog: {
      title: 'Wait!'
    },
    message: 'You forgot to save your details. If you leave now, they will be lost forever.'
  });

  // Bind click event on button
  myform.select("#submit-form").on("click", function() {
    d3.event.preventDefault();
    // validate all forms:
    var form = $('#main-part form')[0];
    var valid = form.checkValidity();
    form.reportValidity();

    if (valid) {
      // Perform submission
      console.log("Form submitted!");

      // set form status back to clean
      $("#" + formId).dirtyForms('setClean');
    }
  });
}
<!DOCTYPE html>

<head>
  <!-- bootstrap -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" crossorigin="anonymous">
</head>

<body style="padding:3%;">
  <div class="container-fluid">
    <div class="row">
      <div id="form-list" class="col-3">
        <div class="table-responsive">
          <table class="table table-striped table-hover table-fit">
            <thead class='thead-dark'>
              <tr>
                <th>Form</th>
              </tr>
            </thead>
            <tbody>
              <tr class="form-name" id="A">
                <td>Form A</td>
              </tr>
              <tr class="form-name" id="B">
                <td>Form B</td>
              </tr>
              <tr class="form-name" id="C">
                <td>Form C</td>
              </tr>
            </tbody>
          </table>
        </div>

      </div>

      <div id="main-part" class="col-9">
        <form>

        </form>
      </div>
    </div>
  </div>


  <script src="https://d3js.org/d3.v5.min.js"></script>
  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.5.0.min.js" crossorigin="anonymous"></script>
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.dirtyforms/2.0.0/jquery.dirtyforms.min.js"></script>
</body>

I need to add a reminder for the user if they forget to submit the form (if the form is dirty) before they click on another form. It can be a popup to let the user choose either to continue (and build the next form) or cancel (return to the current incomplete form).

I have tried to look at the beforeunload feature but it works only when the page is reloaded. In my code, when a form is dirty and user clicks another form, I can console.log('form is dirty');

How do I configure this? I'm using jQuery Dirtyforms


Solution

  • try this

     var isDirty = $("form").dirtyForms('isDirty');
    
    
    if (isDirty) {
      console.log('form is dirty');
       result = window.confirm('You forgot to save your details. If you leave now, they will be lost forever.');
       if(result){
         //implement logic
         $('form').dirtyForms('setClean');
         buildForm(d3.select(this).attr('id'));
       }
       if(!result){
         return
       }
    } 
    //...rest of code