0

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!

3
  • You don't need to wrap your code within a function... Commented Dec 4, 2015 at 10:16
  • When do you want the value to be set in the clientid field? Commented Dec 4, 2015 at 10:17
  • what are you trying to do you want to set value to <input type='hidden' name='clientid' id='clientid' value="test" action="javascript:getHours()" /> which is hidden. Commented Dec 4, 2015 at 10:26

4 Answers 4

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0
$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.

1 Comment

do you see jquery tag
0

Try this

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

<input name='clientid' id='clientid' />

Comments

0

you can use onload() method to call your function getHours(), but .onload() support following tags:
<body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.