1

If you run this test code you will see the date stacked over the the button. I would like the date and button on one line. Please keep in mind this is my first test code with javascript.

<html>

<head>
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write("Today's Date" + month + "/" + day + "/" + year)
//-->

</script>
</head>
<body>

<form name=myform>
<input type=button value="add days" onClick="prompt('How many days do you want to add?','5 or 6');">
</form>


</body>
</html>
  • http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – mpm May 20 '12 at 02:03

3 Answers3

2

Jonathan is right, document.write is really never the best solution unless you are using it to test or something.

just do this instead

    <html>

      <head>
        <script type="text/javascript">
          var currentTime = new Date();
          var month = currentTime.getMonth() + 1;
          var day = currentTime.getDate();
          var year = currentTime.getFullYear();
          var dateString = "Today's Date " + month + "/" + day + "/" + year;
          function loadDate(){
            document.getElementById('dateSpan').innerHTML = dateString;
          }
        </script>

      </head>
      <body onload='loadDate()'> 
        <form name=myform>
          <span id='dateSpan'></span><input type=button value="add days" onclick="promptprompt('How many days do you want to add?','5 or 6')"/>
        </form>
      </body>
    </html>
dano
  • 1,033
  • 1
  • 6
  • 11
1

Don't use document.write. Instead, the more appropriate method would be to use an element on the page:

<form name="myForm">
  <span id="todaysDate"></span>
  <input type="button" />
</form>

At this point, you can assign your date values to the element with an id of "todaysDate":

<script type="text/javascript">
  // Build your variables and message
  var currentTime = new Date();
  var month = currentTime.getMonth() + 1;
  var day = currentTime.getDate();
  var year = currentTime.getFullYear();
  var msg = document.createTextNode("Date: "+month+"/"+day+"/"+year);

  // When the body has loaded, set our message
  document.body.onload = function(){
      document.getElementById("todaysDate").appendChild(msg);
  };
</script>
Community
  • 1
  • 1
Sampson
  • 251,934
  • 70
  • 517
  • 549
  • um, `innerHTML` is also somewhat frowned upon, as it's not valid – Hawken May 20 '12 at 02:31
  • @Hawken Correct. Updated my answer for consistency. Though if I'm not mistaken, `innerHTML` is frowned upon for *getting* values, and not *setting* values. I could be wrong. – Sampson May 20 '12 at 02:35
  • Use ".value" rather than ".innerHTML", as that's standardized, always available, works on all browsers, and is the same word you'd see in HTML. – Chuck Kollars May 22 '12 at 17:07
0

The reason for the overlap you experienced initially is not that the date string lands on top of the button, but the other way around (the button lands on top of the date string). If used at all, document.write() should be placed in the <body> at the exact location where its output makes sense as HTML. Placing it in the <head> makes no sense; your browser is confused by this and blindly tries to execute it immediately anyway but does not update the layout (which apparently isn't even initialized yet), so later the first thing in the <body> (which happens to be the button) overlays it.

Here's what this might look like OLD STYLE. This does not match current best practices coding standards, and should not be emulated exactly. But it may give you a better idea of what's "really" going on. Do note this shows a way to initialize a form withOUT using "innerHTML". It also illustrates a way to label form fields.

I agree that "document.write" shouldn't be used here. It's overly inflexible (always executing when the page is fetched from the server, but probably not executing when the user clicks the "Back" button, and not available to your Javascript program to use for other purposes such as "reset form"). It also in many cases really degrades performance.

It's common both to align all the input fields on a form so they're "pretty" and to draw a box around the entire form. Such things are easy to do; however in order to focus on the area of your question this example does not illustrate them.

It was once possible (and typical) to do this without using getElementById() at all, by naming the form as well as the field within the form, and accessing them with some browser-specific array mumbo-jumbo. But the way with getElementById() is so much simpler and works across all browsers that I won't even illustrate how it used to be done.

The use of window.onload= (note the function name is not followed by an argument list in parens) is no longer the right way to do things. I've used it simply because it's very short and simple, allowing the reader to focus on what really matters.

<html>
<head>
<title>Example of setting a Form Input field</title>
<script type="text/javascript">
function showDefaultDate() {
        var dateInputField = document.getElementById("dateInputField");
        dateInputField.value = provideToday();
}

function provideToday() {
        var currentTime = new Date();
        var month = currentTime.getMonth() + 1;
        var day = currentTime.getDate();
        var year = currentTime.getFullYear();
        var dateString = month + "/" + day + "/" + year;
        return dateString;
}

function initializeForm() {
        showDefaultDate();
}

window.onload = initializeForm;
</script>
</head>
<body>
<form>
Today's Date:
<input type="text" size=" 25" id="dateInputField">
<input type="button" value="Miscellaneous Button">
<br>
Another Field:
<input type="text" size="30">
<br>
<br>
<input type="submit" value="Click Me When Done" style="margin-left: 20ex;">
</form>
</body>
</html>
Chuck Kollars
  • 1,995
  • 19
  • 17