简体   繁体   中英

JavaScript in HTML: Getting undefined input value?

For some reason, when I enter a value in the following script, the value of ISBN is always undefined. I'm not sure why this is the case. I have set the button to run the function onclick as well...

HTML:

<form id="frm1">
    Book ISBN: <input type="text" name="fname"><br><br>
    <input type="button" onclick="myFunction()" value=行きましょう!>
</form>

JavaScript

function myFunction() {
    var isbn = document.getElementById("frm1").submit(); // Replace with ISBN / EISBN / ASIN of the book
    alert("Starting!");
    alert(isbn);

    var api_key = "cf6f5fe91531a855495d77fc06dd9ada6f1fa1f7"; //Replace with the developer key (Submit the form to get a key)

    //Optional Settings
    var smiley = 'true'; // Change to false if do not want to show smiley with each review
    var width = 700;     // Width of the reviews iframe
    var height = 400;    // Height of the reviews iframe
    var wf = document.createElement('script');
    var host = "idreambooks.com";  

    wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
              '://' + host + '/reviews_widget.js?api_key=' + api_key + '&isbn=' + isbn +
              '&smiley=' + smiley + '&width=' + width + '&height=' + height;
    wf.type = 'text/javascript';
    wf.async = 'true';

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(wf, s);
}

Is there anything I'm missing about how to get input values?

var isbn = document.getElementById('someIdYouAssignTheInput').value;

As mentioned above, submit doesn't return anything, which is why the value is undefined. You want to get the value of the input element. The best way to do that is to assign it an id, then use the code I included above.

Good luck!

try

 var isbn = document.getElementsByName("fname")[0].value;

to retrieve the input text box's value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM