JavaScript ផ្ទុកទិន្ន័យជា Array Object ដែលបញ្ចូលទិន្ន័យ

យើងធ្វើប្រអប់មានពីរសម្រាប់បញ្ចូលទិន្ន័យ រួចហើយផ្ទុកទិន្ន័យនៅក្នុង variable ជាប្រភេទ Array Object។ រួចហើយយើងប្រើ forEach ដើម្បីបង្ហាញទិន្ន័យមកក្រៅវីញប្រភេទ list

CSS
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main{
    width: 80%;
    height: auto;
    margin: 20px;
    background-color: white;
    margin-left: auto;
    margin-right: auto;
}
.main .input-form input{
    padding: 20px;
    border-radius: 8px;
    font-size: 18px;
}
.demo ul{
    display: flex;
    list-style: none;
    margin-top: 20px;
    justify-content: space-between;
    display: flex;
    flex-wrap: wrap;
}
.demo ul li{
    background-color: aquamarine;
    padding: 15px;
    border-radius: 5px;
    font-size: 18px;
    width: 49%;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="main">
        <div class="input-form">
            <input type="text" class="labal">
            <input type="text" class="value">
            <input type="button" value="Insert" class="button">
        </div>
        <div class="demo">

        </div>
    </div>
</body>
</html>
JavaScript
<script>
   const btn = document.querySelector(".button")
    const txt = document.querySelector(".labal")
    const val = document.querySelector(".value") 

    var data = []
    btn.addEventListener("click", function(){
        let item = {
            "NAME":txt.value,
            "PRICE":val.value
        }
       data.push(item)
        getData()
    })
    function getData(){
        let text = ""
        data.forEach(d =>{
            text +=`<li>
                    <span>${d["NAME"]}</span>
                    <span>${d["PRICE"]}</span>
                </li>`
        })
        document.querySelector(".demo").innerHTML =`<ul>${text}</ul>`
        
    }

</script>

Post a Comment

0 Comments