HTML 中的 JavaScript:获取未定义的输入值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41988998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript in HTML: Getting undefined input value?
提问by Quinty
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...
出于某种原因,当我在以下脚本中输入值时,ISBN 的值始终未定义。我不确定为什么会这样。我已经设置了按钮来运行 onclick 函数......
HTML:
HTML:
<form id="frm1">
Book ISBN: <input type="text" name="fname"><br><br>
<input type="button" onclick="myFunction()" value=行きましょう!>
</form>
JavaScript
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?
关于如何获取输入值,我有什么遗漏吗?
回答by Tyler Biscoe
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 valueof the input element. The best way to do that is to assign it an id, then use the code I included above.
如上所述, submit 不返回任何内容,这就是该值未定义的原因。您想获取输入元素的值。最好的方法是为它分配一个 id,然后使用我上面包含的代码。
Good luck!
祝你好运!
回答by Loveen Dyall
try
尝试
var isbn = document.getElementsByName("fname")[0].value;
to retrieve the input text box's value.
检索输入文本框的值。

