Chad Verity
Chad Verity

Reputation: 37

Using one script for multiple forms on a single page

I have built a multipage offline mobile webapp in a single html file. Each form requires a timestamp of when the form loads, since it won't be submitted to the server until the user has connectivity sometime later. I'm using the following script to get the timestamp

<script>window.onload = function() {document.getElementById('date').value = Date();}</script>

I use this in each of the four forms:

                    <input name="date" id="date" type="text">

This works well for the first form that is viewed, but doesn't work for any of the other forms. I've tried everything that I can think of but I am a js novice. Thanks for any help.

Upvotes: 1

Views: 37

Answers (1)

tckmn
tckmn

Reputation: 59273

ids must be unique. If you must label multiple elements, use a class instead.

HTML:

<input name="date" class="date" type="text">

JS:

window.onload = function() {
    var currentDate = Date(),
        dateElements = document.getElementsByClassName('date');
    for (var i = 0; i < dateElements.length; ++i) {
        dateElements[i].value = currentDate;
    }
}

Upvotes: 1

Related Questions