简体   繁体   中英

Javascript object not storing data coming from HTML

I am giving two inputs title and status from the HTML. Javascript is listening to the input and creating one emptyObj object to store the values and then appending it to list of objects objList .

Here is something happening like if first time I am giving inputs title: "Node JS" and status: "Pending" the listeners are wokrking fine and I can see them in the objList . But next time if I am appending new item to the list the last input vanishes and only the new one is shown.

Inputs -- HTML Page

HTMML Code --

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <title>Document</title>
    <style>
        #title, #status{
            display: block;
            width: 200px;
        }
    </style>
</head>
<body>
    <div class="divFirst">

    </div>
    <button>You are seeing the pending tasks, please click the button to see completed!</button>
    <input type="text" id="title" placeholder="Please enter the title of the task">
    <input type="text" id="status" placeholder="Please enter the status of the task">
    <script src="DOM.js"></script>
</body>
</html>

javascript code --

let objList = [{
    title: "HTML",
    status: "Completed"
},{
    title: "CSS",
    status: "Completed"
},{
    title: "Javascript",
    status: "Pending"
},{
    title: "React Js",
    status: "Pending"
},{
    title: "Mongo DB",
    status: "Pending"
}]
    let emptyObj = {
        title: "",
        status: ""
    }
    document.querySelector('#title').addEventListener('change',function(e){
        emptyObj.title = e.target.value
        console.log(e.target.value)
    })
    document.querySelector('#status').addEventListener('change',function(e){
        emptyObj.status = e.target.value
        console.log(e.target.value)
    })

    objList.push(emptyObj)

Now, how can I store the values permanently coming from the Inputs?

Thanks in advance!!!

As you are using two onchange methods on two different fields, you will always get the second change wrong. as it will change the title and then insert. You should use a button to update your list.

I think you may achieve your requirement by adding the button under the two inputs

<button id="updateList" onclick="insertEmpty(emptyObj)">Update List</button>

and the following function to DOM.js

function insertEmpty(emptyObj)
{
    objList.push(emptyObj)
    console.log(objList);
}

remove your

objList.push(emptyObj)  // which is currently at the end of your DOM.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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