![](/img/trans.png)
[英]How can I get my input value from input field in a div using JavaScript
[英]How can i get multiple value from an input field using javascript
在我的代碼中,當用戶單擊它時,我有一個添加功能。 它將從文本中捕獲用戶輸入值並顯示。 知道如何使用 javascript 做到這一點嗎?
var split = ['S','M', 'L']; for (var i = 0; i < split.length; i++) { var t = document.getElementById('text-box'); t.innerHTML += 'Size <input value=' + split[i] + ' type="text">Description<input type="text" name="vrow" id="price">' } function add(){ //get the description value }
<div id="text-box"> </div> <button onclick="add()">ADD</button>
(使用香草/純 JavaScript)
首先將id屬性添加到字段,例如
First Name: <input type="text" name="f_name" id="f_name_id">
然后
document.getElementById("f_name_id").value
確保每個字段都有唯一的 ID。
如果你想獲取描述的所有輸入的值,可以使用一個類來獲取所有並迭代
var split = ['S','M', 'L'];
for (var i = 0; i < split.length; i++) {
var t = document.getElementById('text-box');
t.innerHTML += 'Size <input value=' + split[i] + ' type="text">Description<input type="text" class="description-input" name="vrow" id="price">'
}
function add(){
const inputs=document.querySelectorAll('.description-input')
inputs.forEach((input,index)=>{
alert(`value of ${index} description is ${input.value}`)
})
}
這是一種快速獲取表單中所有值的方法,只要您為每個輸入指定一個“名稱”,它就會為您創建一個 JS 對象。
這樣您就不必調用每個單獨的輸入值。 無論您在表單中有多少個 div 或格式化元素,它也將起作用。
<form id="myForm">
<input name="firstname">
<input name="lastname">
<input type="submit" value="Submit">
</form>
<script>
document.querySelector("#myForm").addEventListener('submit',function(event){
event.preventDefault();
var obj = {};
event.target.querySelectorAll('input','select','textarea')
.forEach((v)=>{
if(v.type !== 'sumbit' && v.name){
obj[v.name] = v.value
}
});
console.log(obj);
/* obj
{
firstname: "",
lastname: "",
}
*/
})
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.