Javascript reading html input values

后端 未结 3 807
自闭症患者
自闭症患者 2021-01-07 12:55

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.

相关标签:
3条回答
  • 2021-01-07 13:24

    That's because document.getElementById returns an object of type HTMLElement, which is the element that has the specified ID. To access its value, use this instead:

    var fname = document.getElementById('fname').value;
    

    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:

    function generateBookFootnote()
    {
        var fname = document.getElementById('fname').value;
        var lname = document.getElementById('lname').value;
        var booktitle = document.getElementById('bookititle').value;
        var pubcity = document.getElementById('pubcity').value;
        var pubyear = document.getElementById('pubyear').value;
        var pub = document.getElementById('pub').value;
        var footnote = document.getElementById('footnote').value;
    
        document.getElementById("cite").innerHTML = document.getElementById( fname ).value; 
    
    };
    
    0 讨论(0)
  • 2021-01-07 13:24

    after you select an input element by id with something like:

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

    you can see its current value through the value property. for example:

    console.log(fname.value);
    
    0 讨论(0)
  • 2021-01-07 13:40

    Check your code properly. You've used the object instead of id.

    var fname = document.getElementById('fname');
    
    document.getElementById("cite").innerHTML=document.getElementById( fname );
    

    Use this instead

    document.getElementById("cite").innerHTML=document.getElementById('fname');
    
    0 讨论(0)
提交回复
热议问题