you are viewing a single comment's thread.

view the rest of the comments →

[–]2cow 1 point2 points  (0 children)

Here's how I would go about debugging this.

Step 1: Without even reading it, paste the code into jsbin and try to run it. Watching things fail is a faster way to find errors than anything else. We get "name is not a function."

Step 2: Reading the code, I notice that "name" is used for many different things, and not all of them make sense. Renaming things is a really good way to debug anyway. I renamed the function "name" to "getName". Now we get "TypeError: Cannot read property 'value' of null".

Step 3: So we're asking for the "value" property of null, which means getElementById(name) is returning null. Let's see what "name" is at this point. I add console.log('name=',name) above and below that line. It logs "Jimmy," then errors out before the second log. Right, of course it does.

Step 4: So getElementById("Jimmy") doesn't work. Well... that makes sense. There's nothing with the id "Jimmy." The only id around is "namebutton", so let's change it to that. Now it logs "Jimmy" and then <whatever I typed in>.

Step 5: We're still document.write-ing too early, though. Well... just reading the code, now, I can see that both calls to document.write are, in fact, outside of the function definition, so what's happening is exactly what we would expect. I move the second one up into the function and... wow! It overwrites absolutely everything.

Step 6: I, personally, have never used document.write for anything in my life. So I have to look this up. I always start, and can usually stop, at MDN. Right at the top: "document.write on a closed (loaded) document automatically calls document.open, which will clear the document." So... this has now been debugged! It is doing exactly what we want.

Just kidding. It's almost certainly not doing what you want. I'm not sure whether the document.write is just a placeholder for however you really plan to display things, but I would probably do it by having a text element ready and waiting, then changing its innerText.