summernote-rails
summernote-rails copied to clipboard
Reset file inputs to be friendly to remote forms in Rails
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();
}
});
}
👍
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.
@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