Rails AJAX创建记录后表单无法重置的解决方案咨询
Hey there! The issue with your form reset failing boils down to how you're targeting the form element. Let's break this down and fix it while keeping your destroy logic fully intact.
The Root Cause
Your original code uses document.getElementById('data-js-usercontent-form') to grab the form, but your form doesn't have an id="data-js-usercontent-form" attribute—it only has a data-js-usercontent-form="true" data attribute. That's why the reset method isn't finding the form at all!
The Solution
Since you're already using jQuery and the ajax:success event is bound directly to the form element, you can use $(this) to reference the form inside the callback. This is cleaner and avoids any ID targeting mistakes.
Here's the updated JavaScript code, with only the form reset part modified (your destroy code stays exactly the same):
$(document).on('turbolinks:load', function() { $('[data-js-usercontent-form]').on("ajax:success", function(event, data, status, xhr){ var usercontent = $(xhr.responseText).hide(); $('#usercontents').append(usercontent); usercontent.fadeIn(1000); // Correct way to reset the form $(this)[0].reset(); // Alternatively, you can use: // $(this).trigger('reset'); }); $('[data-js-usercontent-id]').on("ajax:success", function(event, data, status, xhr){ var usercontent_id = xhr.responseJSON.id; $('[data-js-usercontent-id=' + usercontent_id + ']').hide(); }); });
Why This Works
$(this)inside theajax:successcallback refers directly to the form that triggered the AJAX request, so you don't need to hunt for it via ID or data attributes.- The
reset()method (either called on the raw DOM element with[0].reset()or via jQuery'strigger('reset')) will clear all form fields back to their default state—empty text inputs, reset checkboxes/radio buttons to their initial selection, and set select dropdowns back to their first option (or defined default value).
This change will properly clear your form after a successful AJAX submission, while leaving your destroy functionality completely untouched.
内容的提问来源于stack exchange,提问作者Jerome

