我想从html文本框中获取输入并将输出排列在数组中。 我在这里按照这个例子http://www.w3resource.com/javascript-exercises/javascript-array-exercise-13.php
现在我已经能够做到这样的事情,除了我希望它在div标签上打印数组,我似乎没有正确。代码看起来像这样
tidyverse
我想知道为什么不将它打印回div栏
答案 0 :(得分:1)
<!doctype html>
<html>
<head>
<script type=text/javascript>
var array = [];
function add_element_to_array() {
array.push(document.getElementById("institution_name").value);
array.push(document.getElementById("degree_obtained").value);
array.push(document.getElementById("honors_acheieved").value);
document.getElementById("institution_name").value = "";
document.getElementById("degree_obtained").value = "";
document.getElementById("honors_acheieved").value = "";
}
</script>
</head>
<title>Test Javascript</title>
<h1>Test JS</h1>
<body>
<form name="xform" id="xform" method="post" action="samris.php" /> Institution Name:
<input type="text" name="institution_name" id="institution_name" /> </br>
Degree Obtained:
<input type="text" name="degree_obtained" id="degree_obtained" />
</br>
Honors Achieved:
<input type="text" name="honors_acheieved" id="honors_acheieved" />
</br>
</p>
<input type="button" name="Add" id="add" value="add" onclick="add_element_to_array()" />
</form>
<div>
</div>
</body>
</html>
This will be the code. Please check this, maybe it can help. You used x, y and z variable which is not needed at all. Just push the values in the array.
There was another mistake in your code. You declared the array as Array(). It's not correct. In Javascript we can declare an array using Array literal ([]) or new Array.
The array will content all the values. Now you can print it in a div.
答案 1 :(得分:0)
I believe there are 2 problems 1. Your are not initializing the array indices ( x, y and z) at the beginning in your javascript. Please check after modifying your as below
<script type=text/javascript>
var x = 0;
//var y;
//var z;
var array = Array();
function add_element_to_array()
{
array[x++] = document.getElementById("institution_name").value;
array[x++] = document.getElementById("degree_obtained").value;
array[x++] = document.getElementById("honors_acheieved").value;
//x++
//y++
//z++;
document.getElementById("institution_name").value = "";
document.getElementById("degree_obtained").value = "";
document.getElementById("honors_acheieved").value = "";
}
</script>
I do not see any div in your html where you are populating the array contents. You need to assign an id to the div and then add javascript to assign content to that div, something like
document.getElementById('arrayOutput').value = array.toString();