[英]How to get a return value from an input form?
<form>
<input type="number" placeholder="rows" min="1" max="300" id ="RowInput" value="" oninput="rowValue()">
<p>x</p>
<input type="number" placeholder="columns" min="1" max="300" id="ColumnInput" value="" oninput="columnValue()">
<input type="submit" id="Submit" value="" onsubmit="getGridValue()" >
</form>
let tile = document.getElementById("tile")
let rowInput = ''
let columnInput = ''
let gridLength = ''
function rowValue() {
rowInput = document.getElementById('RowInput').value
}
function columnValue() {
columnInput = document.getElementById('ColumnInput').value
}
function getGridLength() {
gridLength = columnInput * rowInput
}
alert(gridLength)
所以我要做的是通過從 columnInput 和 rowInput 獲取值並使用它們來獲取數字來更新 gridLength。 我使用 oninput 事件監聽器來做到這一點,盡管我不確定它是否真的將用戶輸入作為數字返回。 然后當用於將它們相乘時,它們根本不會影響 gridLength 變量。 我不明白我做錯了什么,因為這個想法似乎很簡單。
您可以嘗試如下代碼:
function rowValue() {
rowInput = document.getElementById('RowInput').value;
getGridLength();
}
function columnValue() {
columnInput = document.getElementById('ColumnInput').value;
getGridLength();
}
function getGridLength() {
gridLength = columnInput * rowInput;
console.log(gridLength);
}
如果需要,您可以將 console.log 更改為警報,但 console.log 更好。
我認為唯一引起您問題的是onSubmit。 它應該出現在表單元素內,而不是輸入 type="submit" 元素內。 無論哪種方式,我都做了一些修改和測試,下面的工作就像你想要的那樣:
<form onsubmit="getGridLength();">
<input type="number" placeholder="rows" min="1" max="300" id ="RowInput" value="" oninput="rowValue();">
<p>x</p>
<input type="number" placeholder="columns" min="1" max="300" id="ColumnInput" value="" oninput="columnValue();">
<input type="submit" id="Submit" value="">
</form>
<script>
var tile = document.getElementById("tile");
var rowInput;
var columnInput;
var gridLength;
function rowValue() {
rowInput = document.getElementById('RowInput').value;
}
function columnValue() {
columnInput = document.getElementById('ColumnInput').value;
}
function getGridLength() {
gridLength = columnInput * rowInput
alert(gridLength);
}
</script>
除此之外,我建議使用逗號分隔符 (;) 結束每個 Javascript 命令,就像我在上面的代碼中所做的那樣。 在您將使用的下一個編程語言上,這對您來說也會更容易,因為它們中的大多數都需要在命令末尾使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.