skip to Main Content

I have a form that based on the users clicks, changes some of the labels and placeholder text as well as hides some of the form elements. If the form has a validation error, it resets all of the changes made by javascript back to what originally existed when the form was loaded (i.e the hidden form objects are visible again and the labels/placeholders are changed back to the original text). Is there a way to maintain these changes if a form validation error occurs? Is there a javascript event that is triggered if the form is loaded due to validation error?

I am using vanilla javascript, not jquery.

2

Answers


  1. No, a form validation error would not do that. The page might be reloading after the submit button is clicked and an event triggers to the server.

    Login or Signup to reply.
  2. Unfortunately the classic form submission throws away all changes in the DOM.
    But you can submit the form asynchronously by JS. This way, the changes made by JS will stay on the page. But you will need to use more JS code handle the result of the form submission.

    form.addEventListener('submit', function (event) {
      event.preventDefault();
    
      var formData = new FormData(form);
    
      var xhr = new XMLHttpRequest();
      xhr.open('POST', form.action);
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    
      xhr.onload = function () {
        if (xhr.status >= 200) {
          var response = JSON.parse(xhr.responseText);
    
          if (response.success) {
            // handle successful submission
          } else {
            // handle validation errors
          }
        }
      };
    
      xhr.send(formData);
    });

    And something like this in controller:

    respond_to do |format|
      format.json { render json: { success: true } }
    end
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search