Here is an example
HTML
<input type="text" name="fname" id="fname">
Javascript
function getCookie(something) {
var cookies = {
"username": "John Smith"
}
return cookies[something];
}
function checkCookie() {
var cookieName = getCookie("username");
if (cookieName != null && cookieName != "") {
alert(cookieName);
this.value = cookieName;
} else {
alert("else");
}
}
var fname = document.getElementById("fname");
fname.addEventListener("keyup", checkCookie, false);
On jsfiddle
So based on your comments it maybe that you have not waited until the DOM has loaded before trying to access it.
Here is an example of how to do that.
window.addEventListener("load", function onLoad() {
this.removeEventListener("load", onLoad);
function getCookie(something) {
var cookies = {
"username": "John Smith"
}
return cookies[something];
}
function checkCookie() {
var cookieName = getCookie("username");
if (cookieName != null && cookieName != "") {
alert(cookieName);
this.value = cookieName;
} else {
alert("else");
}
}
var fname = document.getElementById("fname");
fname.addEventListener("keyup", checkCookie, false);
}, false);
On jsfiddle
See:
window.onload
Notes
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.
EventTarget.addEventListener
Summary
addEventListener() registers a single event listener on a single
target. The event target may be a single element in a document, the
document itself, a window, or an XMLHttpRequest.
Why is using onClick() in HTML a bad practice?
Unobtrusive JavaScript