如何从输入表单中获取 return 值?

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。它应该出现在表单元素内,而不是 input 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 命令,就像我在上面的代码中所做的那样。对于您将要使用的下一种编程语言,这对您来说也会更容易,因为它们中的大多数都在命令结束时需要它。