0

I have a form, that has the remote attribute set to true. When I submit it's basically going to save a new "Message" to the database.

However after I send the message, I want to clear the message body that the user typed in. However, it's a little weird to do this

if i use something like this:

$('form').submit(function() {
  $('#text-area').val('');
})

What will happen is that the message body will clear and an empty message will be sent. I want to clear the text area after the form is submitted, not before it's submitted. Any ideas?

Angel Garcia
  • 1,547
  • 1
  • 16
  • 37
  • A quick and dirty fix would be to use `setTimeout` with a delay of 1, or maybe even 0. That will postpone the clearing of the textarea until after the function has ended. –  Sep 12 '19 at 22:49
  • Where are you doing the remote work of adding the message to the database? That would be the place to put the code to clear the message from the field after the message is saved to the database. – hashrocket Sep 12 '19 at 23:00
  • 3
    You need to attach an event handler to the `ajax:success` event. Check out the [docs](https://guides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers). Make sure to read the part on turbolinks if you're using that. – jvillian Sep 12 '19 at 23:50
  • @ChrisG - ew! Personally, I wouldn't call that a fix. But, to each their own. – jvillian Sep 12 '19 at 23:50
  • @jvillian Yep this worked, thanks so much! – Angel Garcia Sep 13 '19 at 00:02

0 Answers0