skip to Main Content

I have a use case where users can add items to a list and remove them, but the list cannot exceed 10 items. I’ve created an Add Item button to add UI elements and a Remove Item button to remove them using the 'display: 'none' property. The issue arises when I add an item with an ID that was previously deleted. In such cases, I’m unable to hide or delete it.

<!DOCTYPE html>
<html>

<head>
    <style>
        div.container {
            width: 100%;
            border: 1px solid gray;
            background-color: silver;
        }

        .button {
            background-color: silver;
            padding: 6px 8px 6px 16px;
            margin-top: 10px;
            color: '#000';
            font-size: 1.2vw;
            margin-left: 20px;
            border: none;
            outline: none;
            font-family: sans-serif;
        }


        .main {
            margin-left: 13%;
            /* Same as the width of the sidenav */
            font-size: 1.5vw;
            padding: 0px 10px;
            margin-Top: 13%;
            padding-bottom: 50px;
            height: 100%;
            /* border: 1px solid blue */
        }

        .submitButton {
            height: 50px;
            width: 40%;
            margin-top: 20px;
            font-size: 20px;
            border-radius: 10px;
            font-family: sans-serif
        }

        .addItemButton {
            height: 40px;
            width: 20%;
            margin-top: 20px;
            font-size: 20px;
            border-radius: 10px;
            align-items: flex-end;
            justify-self: flex-end;
            font-family: sans-serif
        }

        .removeItemButtonView {
            height: 40px;
            width: 20%;
            font-size: 20px;
            border-radius: 10px;
            align-items: flex-end;
            justify-self: flex-end;
            font-family: sans-serif
        }

        .submitButton:hover {
            background-color: #007893;
            color: #fff
        }

        input {
            height: 34px;
            width: 60%;
            text-align: center;
            font-size: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: inline-block;
            vertical-align: middle;
            margin: 10px 0px;

        }

        .inputWidth {
            width: 40%;
        }

        .detailBox,
        .sceneBox {
            display: flex;
            flex-direction: row;
            align-items: flex-end;
            justify-content: space-between;
            border-bottom: 1px solid gray;
            padding: 20px;
        }
    </style>
</head>

<body style="background-color: silver;">
    <div class="container">
        <div class="sticky">
            <header>
            </header>
        </div>
        <!-- <article> -->
        <div class="main">
            <div class="cmdevice">
            </div>


            <button type="button" class="addItemButton" onclick="addItem()">Add Unit</button>

        </div>

    </div>
</body>

</html>

<script>

    let counter = 0
    let deviceArr = []

    const cmdevice = document.querySelector('.cmdevice');

    function addItem() {
        if (deviceArr.length >= 10) {
            return;
        }

        deviceArr.sort((a, b) => a - b);

        let newId = 1;
        for (let i = 0; i < deviceArr.length; i++) {
            if (deviceArr[i] === newId) {
                newId++;
            } else {
                break;
            }
        }

        deviceArr.push(newId);
        console.log('newId', newId)
        let cmItem = document.createElement('div');
        cmItem.setAttribute("id", `cm${newId}`);
        cmItem.innerHTML = `<div style="border: 1px solid; border-radius: 25px; margin: 30px 0px" >
                    <div class="seperator" style="margin: 30px 0px; padding: 0px 20px; display: flex; justify-content: space-between;   align-items: center">
                        <label>Device ${newId}</label>
                        <button type="button" class="removeItemButtonView" onclick="onClickRemoveCMItem(${newId})" >Remove Unit</button>
                    </div>
                    <div class="detailBox">
                        <div>Line Number</div>
                        <br>
                        <input class="input inputWidth" type="text" name="line${newId}" id="line${newId}" value="" />
                    </div>
                    <div class="detailBox" style="border-bottom: 0px" >
                        <div>Area No</div>
                        <br>
                        <input class="input inputWidth" type="text" name="area${newId}" id="area${newId}" value="" />
                    </div>`;
        cmdevice.append(cmItem);
    }

    function onClickRemoveCMItem(id) {
        let ind = deviceArr.indexOf(id)

        console.log(deviceArr, id, ind)
        if (ind !== -1) {
            deviceArr.splice(ind, 1)

            console.log('del', id)
            const a = document.getElementById(`cm${id}`)
            if (a) {
                a.style.display = 'none'
                a.innerHTML = ''
            }
        }

    }

</script>

I have tried various method to delete it. Every ting gives the same result.

3

Answers


  1. When you delete it first time, you’re setting display of ‘cm1’ to none, and when you again add an entry, you create another ‘cm1’; while removing it second time, it finds first ‘cm1’ that’s already lying with display:none and never reaches the current ‘cm1’. Also, it’s not advisable to use multiple elements with same id.

    It’s better to remove it from DOM. Use this instead of setting display

    function onClickRemoveCMItem(id) {
        let ind = deviceArr.indexOf(id)
    
        console.log(deviceArr, id, ind)
        if (ind !== -1) {
            deviceArr.splice(ind, 1)
    
            console.log('del', id)
            const a = document.getElementById(`cm${id}`)
            if (a) {
                a.remove();
            }
        }
    
    }
    
    Login or Signup to reply.
  2. I read your code and executed in my local. So I can find what is the reason of your issue.

    After first removing, assuem that first item, so its id is cm1. When your click the Remove Unit button, following code is executed in if statement.

    a.style.display = 'none'
    a.innerHTML = ''
    

    This work with hidden and clear content, but it don’t remove a in document. So the id cm1 is exists in your html document.

    enter image description here

    So when you click the Remove Unit button secondly, the code works for first element that id is cm1. As a result you can think that dosen’t work.

    To fix this issue, You need to fix the remove logic. Following is my code. Thank you.

        function onClickRemoveCMItem(id) {
            let ind = deviceArr.indexOf(id)
    
            console.log(deviceArr, id, ind)
            if (ind !== -1) {
                deviceArr.splice(ind, 1)
    
                console.log('del', id)
                const a = document.getElementById(`cm${id}`)
                if (a) {
                    // a.style.display = 'none'
                    // a.innerHTML = ''
                    a.remove() // added code
                }
            }
    
        }
    
    
    Login or Signup to reply.
  3. If you just need to hide the element on clicking Remove Unit, then you just need to do this:

      function onClickRemoveCMItem(id) {
        const element = document.getElementById(`cm${id}`);
        if (element) {
          element.style.display = "none";
          element.innerHTML = "";
        }
    

    Suggestion:

    If you wantto actually remove the element rather than just hiding it, then the approach you are following doesn’t seem very optimal. Instead, you can try proceeding like this:

    Give a unique id to your container:

    <div id="device-container" class="cmdevice"></div>
    

    Initializing Variables:

    <script>
      let deviceCount = 0;
      let uniqueIndexCounter = 0;
    
      const cmdevice = document.getElementById("device-container");
      // ....Rest code
    

    Add Device Logic:

    function addItem() {
        if (deviceCount >= 10) {
          return;
        }
    
        deviceCount++;
        uniqueIndexCounter++;
        let cmItem = document.createElement("div");
        cmItem.setAttribute("id", `cm${uniqueIndexCounter}`);
        cmItem.innerHTML = `<div style="border: 1px solid; border-radius: 25px; margin: 30px 0px" >
                        <div class="seperator" style="margin: 30px 0px; padding: 0px 20px; display: flex; justify-content: space-between;   align-items: center">
                            <label>Device ${uniqueIndexCounter}</label>
                            <button type="button" class="removeItemButtonView" onclick="onClickRemoveCMItem(${uniqueIndexCounter})" >Remove Unit</button>
                        </div>
                        <div class="detailBox">
                            <div>Line Number</div>
                            <br>
                            <input class="input inputWidth" type="text" name="line${uniqueIndexCounter}" id="line${uniqueIndexCounter}" value="" />
                        </div>
                        <div class="detailBox" style="border-bottom: 0px" >
                            <div>Area No</div>
                            <br>
                            <input class="input inputWidth" type="text" name="area${uniqueIndexCounter}" id="area${uniqueIndexCounter}" value="" />
                        </div>`;
        cmdevice.append(cmItem);
      }
    

    Remove Device Logic:

      function onClickRemoveCMItem(id) {
        const elementToBeRemoved = document.getElementById(`cm${id}`);
        cmdevice.removeChild(elementToBeRemoved);
        deviceCount--;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search