I am trying to make a Javascript script that asks the user to enter details about a book, and then it generates an MLA style citation for it. The following is my HTML code.
<input type="text" value="Author last name" id="lname"/><br />
<input type="text" value="Title of book" id="booktitle"/><br />
<input type="text" value="City of Publication" id="pubcity"/><br />
<input type="text" value="Publisher" id="pub"/><br />
<input type="text" value="Year of Publication" id="pubyear"/><br />
<input type="text" value="Number of footnote" id="footnote"/>
<br />('Number of footnote' only applicable if you plan to generate a footnote citation.)<br />
<button type="button" onclick="generateBookFootnote()">Generate Footnote</button>
<button type="button" onclick="generateBookEndnote()">Generate Endnote</button>
</form>
<p id="cite"></p>
And my Javascript is as follows.
function generateBookFootnote()
{
//I was just trying to do this, which I got from another StackOverflow question. Result below.
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
var booktitle = document.getElementById('bookititle');
var pubcity = document.getElementById('pubcity');
var pubyear = document.getElementById('pubyear');
var pub = document.getElementById('pub');
var footnote = document.getElementById('footnote');
document.getElementById("cite").innerHTML=document.getElementById( fname );
};
So I’ve tried many approaches from the Internet, trying to just get it to print out the contents of the text box fname. var fname = document.getElementById('fname'); prints out [object HTMLInputElement] not the actual value. The document.getElementById("cite").innerHTML=document.getElementById( fname ); doesn’t print anything when I run the function. Those are the only two solutions I have found on the Internet so far.
That’s because
document.getElementByIdreturns an object of type HTMLElement, which is the element that has the specified ID. To access its value, use this instead:I suggest you to take a look at HTMLElement and getElementById MDN documentations
This issue also applies to either getElementsByClassName, getElementsByTagName and getElementsByName methods, although they all return an array with the matching elements.
Thus, your function should be: