简体   繁体   中英

How can I insert result of JS function in html form?

I have a question - how insert result of JS function in html form? I need to put time (in hh:mm format) into "value" in form. The JS code:

function getHours() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
document.getElementById('clientid').value=h+" "+m;}

The HTML form:

<html>
<form method='post' action='http.example.com/some.php'>
    <input type='hidden' name='clientid' id='clientid' value="test" action="javascript:getHours()" />
</form>
</html>

Thank you for your attention!

You need to load your function like this:

<html>

<body onload="getHours()">
    <form method='post' action='http.example.com/some.php'>
        <input type='hidden' name='clientid' id='clientid' value="test" action="javascript:getHours()" />
    </form>

<script>
    function getHours() {
        var d = new Date();
        var h = d.getHours();
        var m = d.getMinutes();
        document.getElementById('clientid').value = h + " " + m;
    }
</script>
</body>

</html>
$time = h + ':' + m ;
$('#clientid').val($time);

the $time = h + ':' + m ; adds the hours and minute to the format you want to the $time variable.

After that the $('#clientid').val($time); tells JS to add that variable to the clientid 's value.

您可以使用onload()方法调用函数getHours() ,但.onload()支持以下tags
<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

Try this

 <script> document.addEventListener("DOMContentLoaded", function(event) { var name = "Beginner"; document.getElementById("clientid").setAttribute("value", name); }); </script> <input name='clientid' id='clientid' /> 

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