简体   繁体   中英

Ruby on rails render partial does not execute javascript from the main form view

I'm trying to execute JavaScript from the main view form, from the rendered partial when I click on the checkbox in the rendered partial but that JavaScript doesn't execute. It only execute if I copy the content of the partial in the main view. I've searched the site, but I can't get an answer. This is what I have, for example:

app/views/people/_main_form.html.erb

<script>
  view something in partal
  $('people_visible_by_default').click(function(){
    alert("Can you see me");
  });
</script>

<%= bootstrap_nested_form_for @people, html: { class: 'form-horizontal', id: 'people_edit_form' } do |f| %>
   <%=  render partial: 'form_partial', locals: { f: f } %>
<% end %>

The checkbox to be executed in the app/views/people/_form_partial.html.erb

<%= f.check_box :visible_by_default, data: { preview_type: 'none' } %>

clicking on the visible_by_default checkbox doesn't show the alert as I expected.  How do I get it to execute when it is in the main_form.html.erb

I guess you are using id of the checkbox("people_visible_by_default") as the selector in jQuery. But you forgot to append "#" before it.

So, try with

$('#people_visible_by_default').click(function(){
  //your code
});

OR

$('#your_form_ID').on('click', '#people_visible_by_default', function(){
  //your code
});

First of all, you should use the selector you have when loading the main page. Js iterates dom elements when loading main page. So if you rendering something by event (something unexisting in beginning of page loading), there is no js handler. But you can use selector of parent element of rendered partial. For example:

view.html.slim :

.parent_class
  = bootstrap_nested_form_for @people, html: { class: 'form-horizontal', id: 'people_edit_form' } do |f| 
   =  render partial: 'form_partial', locals: { f: f } 

view.js.coffee

$('.parent_class').on 'click', '#people_visible_by_default', (e) ->
  do something 

Try this. I hope it'll help you

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