This particular code might be within the body of the HTML file and this code is executed before the particular HTML elements are created. So, the the value undefined
is assigned to those values.
So, you might want to move the value assignment part within the function itself.
var hours, mins, seconds;
function random()
{
hours = document.getElementById("hrs").value;
mins = document.getElementById("min").value;
seconds = document.getElementById("sec").value;
alert(hours);
alert(mins);
alert(seconds);
}
Note 1: Normally, if you don't use a library like jQuery, code like this is put in onload
. This is what MDN has to say about, when onload is triggered
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading.
So, if you are getting values from the HTML elements, you might want to make sure that we fetch values from them only after the HTML document is completed loaded.
Note 2: Apart from this, you might want to check if you have really set the id
of the HTML elements with hrs
, min
and sec
properly. name
and id
attributes are actually used for different purposes.