简体   繁体   中英

passing value from html to js file

I have a problem with passing value to my js file. I tried do this according to http://feather.elektrum.org/book/src.html and other posts but it doesn't work.

My html file

    <script type="text/javascript">
       var user = 'example_of_user_name';
    </script>
    <script type="text/javascript" th:src="@{/js/file.js}"></script>

and in my file.js I would like to do something like that

   content[0] = '<div class="thumbnail">\
            <form style="display:inline" method="POST" action="/..." class="from-horizontal">\
            <input type="hidden" id="player" value=user name="player" />\
                <button class="btn btn-info" type="submit">Submit</button>\
             </form>\
               </div>'

but this value in my input is always null. When I assign value statically in my input everything works fine.

     <input type="hidden" id="player" value='example_of_user_name' name="player" />\

EDIT:

My namespaces

    <!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
  <html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:th="http://www.thymeleaf.org"
  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

After comments I tried also

      content[0] = '<div class="thumbnail">\
    <form style="display:inline" method="POST" action="/..." class="from-horizontal">\
    <input type="hidden" id="player" value=' + user + ' name="player" />\
        <button class="btn btn-info" type="submit">Submit</button>\
     </form>\
     </div>';

or

    document.getElementById('player').value = user;

but it doesn't work. I still get nullpointer.

Try this

Html

<script type="text/javascript">
   var user = 'example_of_user_name';
</script>
<script type="text/javascript" src="/js/file.js"></script>

Your js file

var content = new Array();

content[0] = '<div class="thumbnail">\
        <form style="display:inline" method="POST" action="/..." class="from-horizontal">\
        <input type="hidden" id="player" value=' + user + ' name="player" />\
            <button class="btn btn-info" type="submit">Submit</button>\
         </form>\
           </div>';

jsfiddle

您可以使用Javascript将值分配给form元素:

document.getElementById('player').value = user;

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