[英]I need help adding data from an external javascript file to a textbox when clicking a button
I have functions built in an external js file and I am trying to create a button that will run that function and then insert the result into a textbox.我在外部 js 文件中构建了函数,我正在尝试创建一个按钮来运行该函数,然后将结果插入到文本框中。
HTML Code: HTML 代码:
<label for="fName">First Name </label>
<input type="text" name="fName" id="fName" /><p>
<input type="button" value="JS Test" name="button1" onclick="writeHumanName(this.form)" />
JS Code: JS代码:
function writeHumanName() {
// Array of my family
var humanName = ["Troy", "Beth", "Gabby", "Owen", "Evan"];
document.write("My Family = ");
// Loop through the humanName array
for (var i = 0; i < humanName.length; i++) {
document.write(humanName[i]);
}
}
Updated:更新:
HTML: HTML:
<label for="fName">First Name </label>
<input type="text" name="fName" id="fName" />
<p>
<input type="button" value="JS Test" name="button1" onclick="writeHumanName()" />
JS: JS:
function writeHumanName() {
// Array of my family
var humanName = ["Troy", "Beth", "Gabby", "Owen", "Evan"];
var myString = ("My Family = ");
// Loop through the humanName array
for (var i = 0; i < humanName.length; i++) {
myString += (humanName[i]) + ", ";
}
document.getElementById('fName').value = myString;
}
A working codepen: http://codepen.io/anon/pen/waLLXO一个工作的codepen: http ://codepen.io/anon/pen/waLLXO
https://jsfiddle.net/ebkd7sp4/8/ https://jsfiddle.net/ebkd7sp4/8/
HTML: HTML:
<label for="fName">First Name </label>
<input type="text" name="fName" id="fName" />
<input type="button" value="JS Test" name="button1" onclick="writeHumanName()" />
JS: JS:
function writeHumanName() {
// Array of my family
var humanName = ["Troy", "Beth", "Gabby", "Owen", "Evan"];
var text = "My Family = " + humanName.join(", ");
document.getElementById("fName").value = text
}
No need to pass anything into your function.无需将任何内容传递给您的函数。 You can use the
join()
command to avoid the loop.您可以使用
join()
命令来避免循环。 Use document.getElementById("fName").value
to manipulate the text in your textbox.使用
document.getElementById("fName").value
来操作文本框中的文本。
Did you include the js file(s) in your index page?您是否在索引页面中包含了 js 文件?
<head>
<meta charset="utf-8">
<title>Hello world</title>
<!-- scripts -->
<script src="js/file1.js"></script> <!-- include files -->
<script src="js/file2.js"></script>
</head>
Edit: It seems you're calling your function from html like so:编辑:您似乎是从 html 调用您的函数,如下所示:
writeHumanName(this.form);
this
will be the window object; this
将是窗口对象; you need to grab the div from the DOM and process it in JS...您需要从 DOM 中获取 div 并在 JS 中处理它...
function writeHumanName() {
// Array of my family
var humanName = ["Troy", "Beth", "Gabby", "Owen", "Evan"],
val = document.getElementById('fName').value;
console.log("My Family = " + val);
// Loop through the humanName array
for (var i = 0; i < humanName.length; i++) {
console.log(humanName[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.