0

I am trying to render a partial inside my js file and append it to my html on a javascript event (click). I tried to follow this and use the escape_javascript method : Rendering partial in js.erb file but unfortunately it doesnt work. This is my js file :

$(document).ready(function(){
      $("#add_resident").click(function(){
          $(".resident").append('<%= escape_javascript(render partial: "resident_form") %>');

        })

})

this is my partial :

<%= label_tag "first name" %>
<%= text_field_tag "resident[:first_name]" %>
<%= label_tag "last name"%>
<%= text_field_tag "resident[last_name]" %>
<%= label_tag "birthdate"%>
<%= text_field_tag "resident[birthdate]" %>

the javascript is indeed triggered on the .click event but it is rendering <%= escape_javascript(render partial: "resident_form") %> as a string. What is the correct way to fix that.

Community
  • 1
  • 1
David Geismar
  • 3,152
  • 6
  • 41
  • 80

2 Answers2

0

Hey your code should be:

$("#add_resident").click();
$(".resident").append('<%= escape_javascript(render partial: "resident_form") %>');

That's all, don't need this code $(document).ready(function(){}), because when server returns this javascript, your view was ready already!

Hieu Pham
  • 6,577
  • 2
  • 30
  • 50
  • Ok but even with the document ready my partial is still not rendering on the string <%= escape_javascript(render partial: "resident_form") %> is rendered – David Geismar May 25 '16 at 09:03
  • Is `$(".resident")` existing? – Hieu Pham May 25 '16 at 09:20
  • yes $(".resident") is existing, the JS is actually triggered on the click event. The problem is that instead of rendering my partial it is rendering <%= escape_javascript(render partial: "resident_form") %> as a string – David Geismar May 25 '16 at 09:28
0

Try this in the JS rendered.

$(".resident").append('<%= escape_javascript(render partial: "resident_form").html_safe %>');
Alok Swain
  • 6,409
  • 5
  • 36
  • 57