提交按钮不会像输入那样清除表单字段

时间:2017-09-28 19:28:35

标签: javascript jquery ruby-on-rails forms

我最初将rails应用程序编码为没有提交按钮,但现在我想使用输入或提交按钮。我的提交按钮将数据发送到我的后端,但它不会清除textfield

形式:

<%= form_for message, remote: true, authenticity_token: true do |f| %>
  <%= f.text_area :content, data: {textarea: "message"}, placeholder: 'Tap the location to send your current location, or tap here to chat.', required: "required" %>
  <%= f.hidden_field :groupchat_id, value: @groupchat.id %>
  <%= f.submit "", class: "send_icon", data: {send: "message"} %>
<% end %>

控制器:

class MessagesController < ApplicationController

  def create
    message = Message.new(message_params)
    message.user = current_user
    if message.save
      ActionCable.server.broadcast "messages_#{message.groupchat_id}_channel",
        message: message.content,
        user: message.user.name
      head :ok
    end
  end

  private

    def message_params
      params.require(:message).permit(:content, :groupchat_id)
    end
end

按Enter键时清除表单的JavaScript:

$(document).on('turbolinks:load', function() {
  submitNewMessage();
  $('#messages').scrollTop($('#messages')[0].scrollHeight);
});

function submitNewMessage(){
  $('textarea#message_content').keydown(function(event) {
    if (event.keyCode == 13) {
        $('[data-send="message"]').click();
        $('[data-textarea="message"]').val("");
        return false;
     }
  });
}

如何设置,以便提交按钮清除文本区#message_content

0 个答案:

没有答案