Marco
Marco

Reputation: 141

how to make Javascript alert box display a variable from Rails controller

I have this piece of Javascript codes in my view file:

<script>
function hint() {
    var str = @user.name;
    var name = str.toLowerCase();

    alert(name);
}
</script>

I want the alert box to display the name of the user so I use the variable @user that was defined in my controller. However, when I click the button to active the alert box, nothing shows up. I also tried current_user.name, but it didn't work either. How can I display the value of a variable in the alert box?

Upvotes: 2

Views: 5118

Answers (3)

user4776684
user4776684

Reputation:

If you have a button then you don't have to write any JavaScript code (assuming a confirmation dialog works for you). You can display a confirmation dialog with data: {confirm: "#{@user.name.downcase}"} passed to your button/submit/link_to helpers:

<%= f.submit 'Save', data: { confirm: "#{@user.name.downcase}" } %>

In addition, it gives you an ability to cancel your button/link click.

Another option without JavaScript is to use onclick event on the button/link:

<%= f.submit 'Save', onclick: "alert('#{@user.name.downcase}');" %>

or pass user name as a parameter to your JavaScript function:

<%= f.submit 'Save', onclick: "your_function('#{@user.name.downcase}');" %>

Upvotes: 1

Bhushan Jadhav
Bhushan Jadhav

Reputation: 21

You can also do like this:

alert("<%= @user.name.downcase %>");

Upvotes: 1

7urkm3n
7urkm3n

Reputation: 6321

Just keep it like this, as like in html file.

 var str = '<%= @user.name %>';

Upvotes: 3

Related Questions