简体   繁体   中英

How to call javascript function from the form attribue value in hhtm?

<html>
    <head>
       <script type="text/javascript">
          function sum() {
              i = 10;
              j = 10;
              result = i + j;
              return result;
           }
       </script>
    </head>
    <body>
       First name: <input type="text" name="fname" value="sum()"><br>
    </body>
</html>

I am new to javascript, I am want to get number value in my input text box.Here I am doing sum of i and j and want there result directly show in the input box without using submit button.

No that won't work. Value of the "value" attribute must be a literal and not function. You need to set the value through javascript on page load:

window.onload = function(){
    document.querySelector("input[name=fname]").value = sum();
};

如果您感觉真的很古怪,可以将标签替换为

<script>document.write('<input type="text" name="fname" value="'+sum()+'"/>');</script>

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