简体   繁体   中英

Javascript not working when page is refreshed (Rails)

On Rails 4, I am trying to submit a form whenever I focus out the input field, without having to click on submit. When I place the script on the html page, it works fine:

      <td>
        <%= form_for commitment, html: {class:"index_edit_comments"}, remote: :true do |f| %>
          <%= f.text_field :comments, class:"index_edit_comments_input" %>
        <% end %>
        <script>
            $(document).ready(function() {    
              $(".index_edit_comments").each(function() {
                $(this).find(".index_edit_comments_input").blur(function() {
                    $(this).submit();    
                });
              });
            });
        </script>
      </td>

But when I move the same code to a separated .js file, it is not functioning properly. It works right after loading the page, but when I use another function that refreshes the page, it stops working. On the .js.coffee file it looks like this:

$(document).ready ->
  $(".index_edit_comments").each ->
    $(this).find(".index_edit_comments_input").blur ->
      $(this).submit()
      return
    return
  return

The other function that refreshes the page is this:

At index.html.erb:

<% if commitment.check == true %>
  <td><%= link_to 'Yes', toggle_check_commitment_path(commitment), type: "button" %></td>        
<% else %>
  <td><%= link_to 'No', toggle_check_commitment_path(commitment), type: "button" %></td>
<% end %>  

At controller:

def toggle_check
  @c = Commitment.find(params[:id])
  @c.toggle!(:check)
  redirect_to commitments_path
end

Thanks for your help. I've did a lot of research and was not able to figure this out by myself.

After page refresh DOM has change, so your cod will not work. Try:

$('html').find('.index_edit_comments').each(function() {
            $(this).find(".index_edit_comments_input").blur(function() {
                $(this).submit();    
            });
          });

If refresh change all DOM html, my code example will not help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM