简体   繁体   中英

Checkbox change event only fire after reloading page



I'm writing an app using Ruby on Rails, there I have a form where if a checkbox is checked it displays a certain <div> and if it isn't I add style="display:none:" through rails. Via Coffeescript and JQuery, I also toggle the same <div> on change.

Coffeescript:

jQuery ->
  $(document).ready ->
    $("#hasUser").change ->
      $("#userPart").toggle();
      return
    return
  return

HTML:

    <div class="form-group">
        <%= contato_form.label :hasUser, :class => 'inline-checkbox' do %>
          Possui usuário <%= contato_form.check_box :hasUser, :id => 'hasUser' %>
        <% end %>
    </div>
</div><!-- Closing from uncopied code -->
<div id="userPart" class="findMe" <% if @contato.usuario.id.blank? %> style="display:none;" <% end %>>
  <h2> Usuário: </h2>
  <div class="container">
    <%= contato_form.fields_for :usuario do |usuario_form| %>
      <%= render partial: 'usuarios/campos_usuario', locals: {form: usuario_form} %>
    <% end %>
  </div>
</div> 


The issue here is that it all runs well when I use the form to Create , but on Edit the Coffeescript only runs after a reload.

It was a turbo-links issue. I had to check if turbo-links was loaded properly before attempting to run the rest of the code.

jQuery ->
  $(document).ready ->
    $(document).on 'turbolinks:load', #Added line
      $("#hasUser").change ->
        $("#userPart").toggle();
        return
      return
    return
  return

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