Celestriel Celestriel - 1 month ago 10
HTML Question

Taking a HTML form <input> value and using it to modify a <p> tag with Javascript

I am fairly new to Javascript and am trying to create a simple madlib application where a user can input a word through an HTML page and have that word appear in a paragraph tag when the user clicks the "submit" button. I am having troubles displaying the word that the user inputs. I know that I am close but for the life of me cannot figure out what I am missing.

Here is the HTML I am using:

<form>
<label>Word</label><input id="word"></input>
<input type="submit" value="submit" id="submitButton"></input>
</form>

<p id="story"> A {userWord goes here} is now part of the story </p>


And the Javascript:

var word = document.getElementById('word').innerHTML,
originalStory = document.getElementById('story'),
button = document.getElementById("submitButton");

button.onclick = function(){
replaceStory(word);
};

var replaceStory = function(userWord) {
var story = ("A " + userWord + " is now part of the story");

return originalStory.innerHTML = story;
};


Here is a JSFiddle: https://jsfiddle.net/5c4j2opc/

Answer

You had a couple of minor problems. The input type of the submit button should be button rather than submit. Submit does a post request and refreshes the page with the data received.

Initially you had: var word = document.getElementById('word').innerHTML this would get the initial innerHTML which would be nothing. You have to get the inner text within word every single time the button is clicked to get the most recent text inside the textbox.

Finally, for a input node you should get .value rather than .innerHTML to get the inner text

html:

<form>
    <label>Word</label><input id="word"></input>
    <input type="button" value="submit" id="submitButton"></input>
</form>

<p id="story"> A {userWord goes here} is now part of the story </p>

javascript:

var word = document.getElementById('word'),
    originalStory = document.getElementById('story'),
    button = document.getElementById("submitButton");

button.onclick = function(){
    replaceStory(word.value);
};

var replaceStory = function(userWord) {
    var story = ("A " + userWord + " is now part of the story");

    return originalStory.innerHTML = story;
};
Comments