Home > Enterprise >  Rails text fields without submit button (auto-submit on input change)
Rails text fields without submit button (auto-submit on input change)

Time:07-05

I am writing a Rails application that has the user entering a 1-digit number, and that number is compared to an "answer" in the database to see if it is correct. I want the comparison to happen instantaneously, as soon as the user enters the number into the field I want the comparison to happen right away.

The way I currently have it setup is the user has to enter the number and click a submit button to submit the form which links to the controller action that checks if it's correct. But I want it to do it automatically on user input, without the need of a submit button.

My form currently:

<%= form_with :controller => "tests", :action => "check_answer", remote: true, local: true, method: 'get' do |f| %>
    <%= f.number_field :answer, :value => '' %>  
    <%= f.submit 'Submit' %>
<% end %>

Ideally I would like to do this without the use of JavaScript or jQuery, but can use it if need be. Any help is greatly appreciated.

CodePudding user response:

I don't see a way to do this without js. Try something like:

<%= f.number_field :answer, value: '', onchange: "this.form.submit()" %>

Or maybe use onkeyup instead of onchange.

CodePudding user response:

You can use Stimulus auto save, Stimulus is the default js library on rails 7.

  • Related