[英]To get value of user input from input
我正在學習 Javascript 並試圖從輸入中獲取用戶輸入值。
在我的項目中,我有一個輸入表單,當他們添加新數字並單擊一個按鈕時,會出現新表單,用戶可以輸入另一個數字,只要用戶單擊按鈕,新輸入字段就會繼續出現。
我想要的是從每個輸入中獲取價值。 我看到一些問題提出了類似的問題,但 .document.getElementsByName() 對我不起作用。
let userInput = document.getElementsByName('moneyamount');
inputNum = parseInt(userInput.value);
console.log(inputNum); //result is NaN
我也試過 document.querySelector()
let userInput = document.querySelector('#money-amount');
inputNum = parseInt(userInput.value);
console.log(inputNum)
效果很好,但我需要從一些輸入中獲取價值,因此 querySelector 不適用於這種情況。 所以我也嘗試了 document.querySelectorAll() ,但是,
let userInput = document.querySelectorAll('#money-amount');
inputNum = parseInt(userInput.value)
console.log(inputNum)// result is NaN
我不確定在這種情況下應該使用什么 DOM。 我需要選擇所有元素並需要從中獲取價值。
這是我的輸入 HTML。 此時只有一個輸入,因為當用戶單擊添加按鈕時,將添加新表單。
<input
class="input money"
type="number"
id="money-amount"
placeholder="Enter amount"
name="moneyamount"
required
/>
</div>
我希望你們能幫助解決這個問題。
非常感謝!
我覺得你處理這個問題的最好方法是編輯 div 的innerHTML。
例如:
<div id="allTheForms">
<form action="#" onsubmit="addForm();">
<input type="text">
<button type="submit">Submit</button </form>
</div>
<script>
function addForm() {
var currentHTML = document.getElementById("allTheForms").innerHTML;
var newForm = '<form action="#" onsubmit="addForm();"><input type="text"><button type="submit">Submit</button</form>';
document.getElementById("allTheForms").innerHTML = currentHTML + newForm;
}
</script>
這應該允許你做我認為你在問的事情。
您可以執行document.getElementById("money-amount").value
從輸入中獲取金額。 如果您要求來自多個輸入的值,您應該這樣做。
var userinputs = [];
function getInputs() {
var elem = document.getElementsByClassName("input money");
for (var i = 0; i < elem.length; i++) {
if (typeof elem[i].value !== "undefined") {
userinputs.push(elem[i].value);
}
}
}
然后要訪問第一個金額,您可以執行userinputs[0]
,依此類推。
嘗試這個
<input type='text' required id='input' onchange="check()"> <p id='output'>null</p> <!-- the javascript --> <script type='text/javascript'> function check(){ //set the value as a let let input = document.querySelector('#input').value; //show it document.querySelector('#output').textContent = input; } </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.