简体   繁体   English

动态表单输入值未更新 Javascript Object

[英]Dynamic Form Input Value not updating Javascript Object

new coder here.新编码器在这里。 I've spent a week trying to get this to work and really need help.我花了一周的时间试图让这个工作,真的需要帮助。 I have a form with one input field.我有一个带有一个输入字段的表单。 I can query it and get the new name values.我可以查询它并获取新的名称值。

Problem is when I use the same query in a object literal key/value pair, it doesnt show the updated values when you change the values.问题是当我在 object 文字键/值对中使用相同的查询时,当您更改值时它不会显示更新的值。 It only shows the original values when I console.log.它仅在我 console.log 时显示原始值。 Any help would be greatly appreciated.任何帮助将不胜感激。

HTML HTML

<form id="nameForm" class="nameForm" action="#">

<label id="nameLabel" for="nameInput">Enter Your Name:</label>

<input type="text" id="nameInput" class="nameInput" required>

<button id="next" type="button">Next</button>
</form>

JavaScript JavaScript

let salonOwner = {

name: document.querySelector(#nameInput).value

}

So basically javascript file run only once so you need to add EventListener to listen when you submit the form and update salonOwner through it所以基本上 javascript 文件只运行一次,所以你需要在提交表单时添加 EventListener 来监听并通过它更新 salonOwner

<form id="nameForm" class="nameForm" action="#">

    <label id="nameLabel" for="nameInput">Enter Your Name:</label>
    
    <input type="text" id="nameInput" class="nameInput" required>
    
    <button id="next" type="submit">Next</button>
</form>
let salonOwner = {
  name: ""
}

//Initilize Dom Element
let form = document.querySelector("#nameForm")


//Add EventListener to Update The salonOwner Object
form.addEventListener("submit" , (e)=>{
  let name = document.querySelector("#nameInput").value;
  salonOwner.name = name;
})

You need for your button an onclick-event, which calls your new function update.您的按钮需要一个 onclick 事件,它调用您的新 function 更新。 So everytime it is pressed your object will be updated.所以每次按下你的 object 都会更新。

<form id="nameForm" class="nameForm" action="#">
    <label id="nameLabel" for="nameInput">Enter Your Name:</label>
    <input type="text" id="nameInput" class="nameInput" required>
    <button id="next" type="button" onclick="update();">Next</button>
</form>

<script>
    function update() {
        let salonOwner = {
            name: document.querySelector("#nameInput").value
        }
        console.log(salonOwner);
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM