2

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?

3 Answers 3

3

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

 var str = '<%= @user.name %>';
Sign up to request clarification or add additional context in comments.

Comments

1

You can also do like this:

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

Comments

1

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}');" %>

Comments

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.