Reputation: 141
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
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
Reputation: 21
You can also do like this:
alert("<%= @user.name.downcase %>");
Upvotes: 1
Reputation: 6321
Just keep it like this, as like in html file.
var str = '<%= @user.name %>';
Upvotes: 3