0

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.

2 Answers2

1

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>
Gonzalo Robaina
  • 367
  • 3
  • 15
  • This definitely did help. it works now. However, it doesn't take the information of the text field. It is always an "empty" paste. This may just now come down to the JS function itself. – Mislav Rukonic Mar 21 '22 at 15:24
  • @MislavRukonic please refer to this other question: https://stackoverflow.com/a/10972973/587518 it seems the onpaste event gets fired before the field value gets the pasted value. – Gonzalo Robaina Mar 21 '22 at 20:30
  • Thanks for the response. I checked out this post, and it seems that this was exactly what I was looking for. Cheers! – Mislav Rukonic Mar 21 '22 at 21:33
0

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