Вопрос

I'm using escape_javascript in a js.erb file in order to load a partial with AJAX :

$("#datas-user").html("<%= escape_javascript(render :partial => '/pro/users/show_partial', :locals => { :id => @user.id }) %>");

My issue is that the javascript used in my partial seems to be broken?

In my view, I have a button id="relation-contact-button" using jQuery Hide function to show a div loaded in display: none

my partial :

<div class="row">
<div class="col-xs-7">
    <div class="user_name"><%= @user.firstname %> <%= @user.lastname.chr %>.</div>
</div>
<div class="col-xs-5">
    <div id="relation-contact-button" class="btn btn-blue">Contact</div>
</div>
</div>

<div id="relation-contact" class="rows">
<div class="col-xs-12 col-lg-12">
<%= form_for :message, url: pro_messages_path do |f| %>
<%= f.label :message, :class => "search-title" %>
<div class="form-group">
<%= f.text_area :message, :rows => 2, :class => "form-control", :placeholder => "Expliquez ce que vous pouvez apporter à cette personne" %>
</div>
<%= f.hidden_field :user_id, :value => @user.id %> 
<%= f.submit "Envoyer", :class => "btn btn-blue" %>
<% end %>
</div>
</div>

my css :

#relation-contact {
display: none;

}

my js :

$("#relation-contact-button").click(function(){
    $('#relation-contact').show();
});

When I use the same code without the partial it works, with it nothing happens.

Is there a way to render my partial and keep my js working?

Thanks a lot.

F

Это было полезно?

Решение

This is what happens:

After your site was loaded, your js kicks in and binds the click event handler to #relation-contact-button. Then you do whatever and call your ajax handler

$("#datas-user").html("<%= escape_javascript(render :partial => '/pro/users/show_partial', :locals => { :id => @user.id }) %>");

everything inside #datas-user is removed and replaced with your partial and no event listener is bound to anything, since the element which your handler was bound to is gone. You have to either bind your handler to the newly rendered #relation-contact-button again in your ajax success handler, or use:

$("#datas-user").on("click", "#relation-contact-button", function(){
 $('#relation-contact').show();
});

instead of

$("#relation-contact-button").click(function(){
 $('#relation-contact').show();

See the .on() doc for more information.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top