سؤال

I am using ajax to update some form fields.

One of the fields is the following

<td id='alarms_id'></td>

In file update.js.erb, I have the following :

alert('<% concat @alarms %>')
document.getElementById("alarms_id").innerHTML = '<% concat @alarms %>'

In the controller, if I do the following (for testing purposes)

@alarms = "Hello World!"

all will work fine, I see the alert popup window, and I see the field showing "Hello World!" message. But in my real application, I want all alarms to be in separate lines, so I tried this:

@alarms = "Hello \n World!"

but then I don't see the alert message and my field is not updated (no Hello World message shows up). I tried Firefox and Safari and none worked for me.

Anyone understands what am I doing wrong, and how can I get the "Hello World!" message to show in 2 separate lines?

هل كانت مفيدة؟

المحلول

In Ruby on Rails, you can do it in several ways:

Use html_safe to mark your HTML variable:

@alarms = "Hello <br/> World!".html_safe
document.getElementById("alarms_id").innerHTML = 'concat <%= @alarms %>';

Or use html_safe to display your HTML variable:

@alarms = "Hello <br/> World!"
document.getElementById("alarms_id").innerHTML = 'concat <%= @alarms.html_safe %>';

Or use raw to display your HTML variable:

@alarms = "Hello <br/> World!"
document.getElementById("alarms_id").innerHTML = 'concat <%=raw @alarms %>';

Notice that the alert() function in JavaScript does not understand HTML code, so you cannot use it to display your HTML variable as is.

نصائح أخرى

In HTML, you write a line break like this: <br/> not \n.

Instead of @alarms = "Hello \n World!" have you tried @alarms = "Hello <br> World!"?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top