PDA

View Full Version : Java in HTML Text Box



ronh100
Mar 22nd, 2013, 08:54 PM
Can someone show me how to write a form input text box html code that will display the results of this script in the html text box? Thank you.

[CODE]<script type="text/javascript">
<!--
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + month + "/" + day + "/" + year + "&nbsp;" + "</b>")

var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()

if (minutes < 10)
minutes = "0" + minutes

var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
//-->
</script>[CODE]

WolfShade
Mar 22nd, 2013, 09:00 PM
You don't need to use separate variables (currentDate/currentTime) for time and date. Just set rightNow = new Date() and get everything off of that.

document.write is not a good idea. If it is run after a page loads, it overwrites the whole page (including the javascript that generated it.) Use modern day DOM methods (create a div, give it an id, and set the innerHTML of that id to what you want.)

If you need to set the value of a text input, give the input an id and use document.getElementById(' input name ').value = "foo";

ronh100
Mar 23rd, 2013, 02:25 AM
Thank you Wolfshade for your help but I am a JavaScript newbie and what you said is mostly Greek to me. Can you show me what that would look like with the changes you described. I would be very grateful. Thank you.

felgall
Mar 23rd, 2013, 03:13 AM
Modernising the code slightly to get rid of the HTML comment to hide the script from Internet Explorer 2 and wrapping it inside a function to make it unobtrusive and to define all the local variables at the top in one go - you end up with the following:


<b id="dt"></b><b id="tm"><b>
<script type="text/javascript">
(function() {"use strict";
var currentDate, day, month, year, hours, minutes, suffix;
currentDate = new Date();
day = currentDate.getDate();
month = currentDate.getMonth() + 1;
year = currentDate.getFullYear();
document.getElementById('dt').innerHTML = month + "/" + day + "/" + year;

hours = currentDate.getHours();
minutes = currentDate.getMinutes();

if (minutes < 10)
minutes = "0" + minutes;

suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.getElementById('tm').innerHTML = hours + ":" + minutes + " " + suffix ;
})();
</script>