<li><form name="project5" id="partTwo" onSubmit="return project5Part2();" >
<label for="userInput">name:</label>
<input type="text" id="userInput"/>
<input type="submit" />
</form></li>
</ul>
<div id="outputDiv" class="output" >
<p id="numberName"></p>
<table id="outputTable"></table>
</div>
<script language="JavaScript" type="text/javascript">
project5Part2();
</script>
// global variable
var userEnteredName = [];
function addInput() {
var input;
input = document.getElementById("userInput");
userEnteredName.push(input.value);
}
function printToTable() {
var outputTable;
outputTable = document.getElementById("outputTable");
var numbersOfName;
numbersOfName = document.getElementById("numberName");
numbersOfName.innerHTML = "numbers of name:" + userEnteredName.length;
outputTable.innerHTML = "<th>" + "Name" + "</th>";
for(index = 0; index < userEnteredName.length; index++) {
outputTable.innerHTML +="<tr><td>" + userEnteredName[index] + "</td></tr>";
}
}
/*
This is the JavaScript code for
"Name Entry"
File: /unit5/project/project5Part2.html.
The purpose of this function is to
*/
function project5Part2() {
addInput();
printToTable();
return false;
}
img是我从代码到网页的内容。
没有价值,但arrar.length已经存在 我需要它为0并开始计数,因为我输入值到文本框并推进它通过它
答案 0 :(得分:0)
确定如何在页面加载后运行函数project5Part2()
,然后调用:addInput()
。您遇到的问题是addInput
不检查输入是否为空,并将""
添加到您的全局数组 userEnteredName
。
您生成的数组大小为1,看起来像[""]
。
function addInput() {
var val = document.getElementById("userInput").value;
// Check if value exists and is of a non-zero length, then push to array
val && userEnteredName.push(val);
}
现在你的addInput
函数只会存储非空字符串(即当输入框中实际输入的内容时)
有意义吗?
HTML的新变化:
function clearForm() {
document.getElementById("userInput").value = ""
userEnteredName = []
}
<li><form name="project5" id="partTwo" onSubmit="return project5Part2();" >
<label for="userInput">name:</label>
<input type="text" id="userInput"/>
<input type="submit" />
</form><button onclick="clearForm()">Clear</button></li>
</ul>
<div id="outputDiv" class="output" >
<p id="numberName"></p>
<table id="outputTable"></table>
</div>
<script language="JavaScript" type="text/javascript">
project5Part2();
</script>