summernote-rails icon indicating copy to clipboard operation
summernote-rails copied to clipboard

Reset file inputs to be friendly to remote forms in Rails

Open m5rk opened this issue 9 years ago • 3 comments
trafficstars

Suppose you have a summernote editor in a remote form:

= simple_form_for my_thin, remote: true do |sf|
  = sf.input :text, as: :summernote

When you insert an image with the image button in the toolbar, the input[type="file"]' input will not be blank causing jquery-ujs to fail to handle the form submission remotely, instead submitting it as html.

I fixed this with an onImageUpload callback; the key part below is wrapping the file inputs in a form and resetting the form:

      onImageUpload: function(files) {
        var $editor = $(this);
        var data = new FormData();
        data.append('file', files[0]);

        $.ajax({
          url: '/uploads',
          type: 'post',
          data: data,
          processData: false,
          contentType: false,
          success: function(response) {
            var imageUrl = response.url;
            $editor.summernote('insertImage', imageUrl);
            var form = $editor.parents('form');
            // Credit to: http://stackoverflow.com/a/13351234
            var fileInputs = form.find('input[type="file"]');
            fileInputs.wrap('form').closest('form').get(0).reset();
            fileInputs.unwrap();
          }
        });
      }

m5rk avatar Jan 21 '16 14:01 m5rk

👍

solisoft avatar Apr 23 '16 20:04 solisoft

We can reset the file input like summernote does

onImageUpload: (files) ->
  form_data = new FormData()
  form_data.append('image', files[0])

  # el is the textarea
  $editor = el.data('summernote').layoutInfo.editor
  $file_input = $editor.find(':file')
  $file_input.replaceWith($file_input.clone().val(''))

This will only reset file inputs in summernote editor, more safer.

greatghoul avatar Aug 12 '17 18:08 greatghoul

@m5rk

           var form = $editor.parents('form');
            // Credit to: http://stackoverflow.com/a/13351234
            var fileInputs = form.find('input[type="file"]');
            fileInputs.wrap('form').closest('form').get(0).reset();
            fileInputs.unwrap();

This code wrap my other form which is also present in the page

rahul-kewalramani avatar Jan 11 '23 12:01 rahul-kewalramani