EDIT thanks to everyone!
I have a cookie on a page and when the page loads I want to put the value from the cookie into a input box as its defualt value.
However it will not work and I cant find the problem. I even made a test div and tried to change that but it wont work.
function checkCookie() {
var cookieName = getCookie("username");
if (cookieName != null && cookieName != "") {
alert(cookieName);
document.getElementById("fname").value = cookieName
} else {
alert("else");
return;
}
}
Here is the html
<input type="text" name="fname" id="fname" onKeyUp="isName(this.value)">
I tried this code as well (I just made a div called tester2
document.getElementById("fname").value = "hello"
doesnt work
document.getElementById("tester2").innerHTML = cookieName
doesnt work
Nothing works. It will not let me change a element within this function. If I try and put the code (ie document.etcetc.innerHTML = "hi") in another function then it works perfectly... however it will not run as shown above. Its driving me crazy.
Any ideas?
I suspect that when the checkCookie
function executes, the DOM is not ready yet and your input doesn't exist.
To make sure it's not the case, try the following:
window.onload = checkCookie;
This will execute the checkCookie
function only when the window content has been loaded. It is not the most efficient way to do it, but since I don't know which browser you are using, it was the most reliable way to test.
EDIT: After taking a look at your code, the problem is this line:
window.onload = checkCookie();
That will execute the checkCookie
function right away and try to assign the function's result to window.onload
.
Check in my previous example to see how it should be done.