简体   繁体   中英

pass variable from html to javascript

<%= semantic_form_for :.........  do |f| %>
<%= f.inputs do%>
    <%= pluralize @size, 'Profitable Routes to test'%>
    <p>User id: <%= @id %><p>
    ....

<title> audio player</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link href="/skin/pink.flag/jplayer.pink.flag.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
    $(document).ready(function(){
        var u_id = document.getElementById('id')
        $("#jquery_jplayer_1").jPlayer({
            ......
                ......
                ......
                .......
        });
    });
        //]]>
    </script> 

I want to pass the User id to javascript, i'm trying to do it with this: var u_id = document.getElementById('id') but it says that u_id is null, who can i pass it? Thanks!

You should write the variable directly in the JavaScript code:

var u_id = <%= @id %>;

Actually when you use document.getElementById() in JavaScript you get a DOM element. And not the variable @id . The variable @id doesn't event exist for JavaScript.

Why?

I guess you're using Rails. @id is a Rails variable. Rails compiles the templates (on the server) before sending the final html page to the user. It means it replaces all the <% %> by the results of each block which are plain text.

The JavaScript is then run on the client browser. It's not aware of Rails.

When you do var u_id = <%= @id %>; Rails compiles it in something like var u_id = 198297; which is send to the client browser. Then JavaScript is happy, the variable is correctly set.

u_id is the dom element . you should select a attr of this element

u_id.value

or

u_id.innerHTML

in jquery :

u_id.val()
u_id.html()

document.getElementById('id') is the element, not its value. You should use something similar to

id = document.getElementById('id').innerHTML;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM