Home > Blockchain >  How to have JS onpaste event work with Rails form?
How to have JS onpaste event work with Rails form?

Time:03-21

I have a search form, and would like it so that when I paste something into the form, it automatically submits the form. I would also like to retain functionality so if I don't paste something, and rather manually type it, that I have to press enter/search button for it to work.

Here is my form:

<h1 class = "CustomerTitle">Search Tool</h1>
<%= form_with url: "/support/search_res", class: "form", method: :get do |form| %>
  <%= form.text_field :query, class: "input", placeholder: "Search for a user..." %>
  <%= form.submit "Search", class: "submit_button", id: "pasteSubmit", onpaste: 'pasteAndGo()' %>
<% end %>

<script>
  function pasteAndGo() { 
    document.getElementById('pasteSubmit').submit(); 
  }
</script>

Could somebody tell me why this is not working?

Edit: I've tried Sercan Tırnavalı's approach:

<h1 class = "CustomerTitle">Revuto Customer Support Tool</h1>
<%= form_with url: "/support/search_res", class: "form", onpaste: 'pasteAndGo()', method: :get do |form| %>
  <%= form.text_field :query, class: "input", placeholder: "Search for a user..." %>
  <%= form.submit "Search", class: "submit_button" %>
<% end %>

<script>
  function pasteAndGo() { 
    document.getElementsByClassName('form')[0].submit(); 
  }
</script>

with no progress. Any other ideas/solutions are appreciated.

CodePudding user response:

You should select form and submit it, not the button.

<script>
  function pasteAndGo() { 
    document.getElementsByClassName('form')[0].submit(); 
  }
</script>

Also you can use this js library for this type functionality https://select2.org/data-sources/ajax

CodePudding user response:

I believe you have the onpaste in the wrong place. Please try this:

<h1 class = "CustomerTitle">Revuto Customer Support Tool</h1>
<%= form_with url: "/support/search_res", class: "form", method: :get do |form| %>
  <%= form.text_field :query, class: "input", placeholder: "Search for a user...", onpaste: 'pasteAndGo()' %>
  <%= form.submit "Search", class: "submit_button" %>
<% end %>

<script>
  function pasteAndGo() { 
    document.getElementsByClassName('form')[0].submit(); 
  }
</script>
  • Related