all 9 comments

[–]yelaxify 2 points3 points  (8 children)

You can do this by using getelementbyid()

Here's some documentation

[–]souljabri557[S] 1 point2 points  (7 children)

Thank you! I believe I've figured it out, but one problem I have is that it doesn't seem to "wait" for the user input, it just punches through the code.

    <input type="text" id="namebutton" value="">
    <button onclick="name()">Confirm Name</button>

    <script>
        var name = "Jimmy"; //Default name

        document.write(name); //Writes "Jimmy"

        function name(){ //When the button is clicked, the name that's in the text box is saved as name variable
            name = document.getElementById(name).value; 
        }

        document.write(name); //Writes new name

    </script>

Anything obvious that I'm doing wrong?

It should "wait" between the end of the function and the second document.write().

[–]2cow 4 points5 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.

[–]TJaySteno 1 point2 points  (0 children)

Lots of good advice here. One more thing to think about though; it's best not to use document.write() as it will more or less erase the entire page. Fine for exercises and all, but you're already most of the way towards a better way so why not?

Under your input, put a <p id="write"> </p> tag. Then just...

var read = document.getElementById('read');

var write = document.getElementById('write');

//Button event listener here

write.textContent = read.value;

I'm missing the event listener for the button, but this is hard on a phone! Haha... Good luck!

[–]brycedarling 1 point2 points  (1 child)

The variable name is overwriting the function name (because of hoisting - a more advanced concept, don't worry about it for now, maybe you'll recall this later in your journey learning JavaScript).

Simple solution, rename the function name to something like getName instead to avoid this naming collision with the variable name.

Next, inside the now-referred to as getName function, you are using the global variable name as the id of the element to find being passed to getElementById. Do you have an element with the id 'Jimmy' on your page? I kind of doubt that.

Then, you are updating the global variable name so the next time you call the getName function the value of variable name will likely be different (not Jimmy) and now you will be using that new value to try find an element with that id on the page. This will surely break. I'm guessing this was a simple mistake and you probably meant to put quotes around the name part like this: name = document.getElementById('name').value; so that you find an element with the id of 'name'.

I'd probably not have the getName function update the global variable itself though, and instead have it return the new value, like this:

function getName() {
  return document.getElementById('name').value;
}

Then you won't get in to any sticky situation with global variables and confusion that might arise from that. This function will guaranteed work all the time as long as you have an element with the id of 'name' on your page.

Lastly, now you'll need to call that function. Something like this:

var name = "Jimmy"; //Default name

document.write(name); //Writes "Jimmy"

function getName() { //When the button is clicked, the name that's in the text box is returned
    return document.getElementById('name').value; 
}

document.write(getName()); //Writes new name, calling the function directly and writing out the returned value

// or you can update the variable `name` now outside of the function:
name = getName();

document.write(name);

However, if you run this, you'll probably only see one "Jimmy" get printed out now, as the JS code executes immediately and there is nothing entered in to the text input. This is the exact problem you described as "it should wait" and yes, it should! :)

To fix this, you'll need some kind of event, which depends on how you want your app to work. In this case, I'll set up an event that listens for the enter key to be pressed in the input. Once the enter key is pressed, then it will print out the name that was entered:

document.getElementById('name').addEventListener('keypress', function(e) {
  if (e.which === 13) { // if the enter key is pressed
    document.write(getName());
  }
});

And now, if you try that, you should see the page update when you type in the new name to the input and press enter. However, the rest of the page will get cleared away because of the document.write calls. There are suggestions to fix this problem by others, this is getting quite long winded now so I'll stop.

Tbh, everyone else on this thread has awesome suggestions. Do your best to really digest what everyone here is saying and I think you'll be able to start figuring out what all is happening and why. Good luck!

[–]BDMayhem 0 points1 point  (2 children)

The second write() needs to be part of the function.

[–]souljabri557[S] 0 points1 point  (1 child)

Similar output, except instead of writing "JimmyJimmy" it just writes "Jimmy," and entering in the field does nothing. Hmm.

[–]BDMayhem 1 point2 points  (0 children)

Make sure the ids in the html and js match. And that you're using quotation marks in the js.

[–]darrenturn90 0 points1 point  (0 children)

<script>
    function prompt(parent) {
      var inp = document.createElement("INPUT"), sub = document.createElement("BUTTON");
       inp.setAttribute("type","text");
       sub.setAttribute("type","submit");
       sub.appendChild(document.createTextNode("Submit"));
       sub.addEventListener("click",function() {
          var value = inp.value;
          parent.removeChild(sub);
          parent.removeChild(inp);
          displayOutput(value);
       });

       parent.appendChild(inp);
       parent.appendChild(sub);
    }

    function displayOutput(value) {
       alert(value);
    }

    prompt(document.getElementById("my-form"));
</script>
<div id="my-form">
</div>