2

Why isn't this passing text to javascript/jquery.? @i[:error] definitely has a string in it, I can print that on console.

js.erb file -

<% if @i[:error] != "" %>
<% puts "--> " + @i[:error]  %>
#--> error
#Validation error(s):
#-  Item Is not defined or blank. # that's the error string in @i[:error]

$(function() {
$("#error_message").attr("class", "message_error");
$('#error').text("<%= @i[:error]%>"); #Not working for @i[:error]
#$('#error').text("<%= "#{@i[:error]}"%>");#Not working for @i[:error]

#$('#error').text("Test"); #This is working
#$('#error').text("<%= "?????"%>"); #This is working
});
<% else %>
........#fine here
<% end %>

2 Answers 2

2

Yes, it's probably because of the line break. You can fix it by using escape_javascript.

Escapes carriage returns and single and double quotes for JavaScript segments.

So:

$('#error').text("<%= escape_javascript(@i[:error]) %>");
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that is what it was. line break was causing the issue. You solved it.
0

If you specify what debugger says it would be easier to understand the problem. This code for erb views works fine:

<% @i = {} %>
<% @i[:error] = "Error" %>  

<% unless @i[:error].blank? %>
  <script>
    $(document).ready(function() {
      $('#error').text('<%= @i[:error] %>'); // Works fine
    });
  </script>
<% end %>

Pay attention that emptiness of string is checked by blank? method, I think it look much nicer than using != operator.

2 Comments

Don't know what is wrong there. I tried your change but no luck.
Can this be because of line break in the string that javascript cannot accept?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.