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

I have this piece of Javascript codes in my view file:<script>function hint() {var str = @user.n

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?

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?

Share asked May 28, 2016 at 16:18 MarcoMarco 1415 silver badges14 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

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

You can also do like this:

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744915309a4600797.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信