Home  >  Q&A  >  body text

Add extra checkboxes to implement previously checked/unchecked functionality

<p>This form is a to-do list with HTML/CSS/JavaScript, and each row has a checkbox based on completed or unfinished tasks. I created an event. It gets some values ​​from an object, like text, creation time, ID, etc., and finally appends a li tag to <strong>inner HTML =<code>...</code></strong> . If I have the previous checkbox checked in </p><li> but when the event is triggered (button pressed) the new row is added unchecked (which is normal) but the previous One row of checkboxes is also unchecked! ? <p><br /></p></li>
P粉765570115P粉765570115433 days ago427

reply all(1)I'll reply

  • P粉381463780

    P粉3814637802023-08-14 12:26:26

    Here is a quick code snippet that replicates your problem. Run it and then make a check element on the checkbox. Notice that checking/unchecking the checkbox doesn't change the HTML code you're checking?

    "use strict";
    window.addEventListener('load', onLoaded, false);
    
    function onLoaded(evt)
    {
        document.getElementById('addNewBtn').addEventListener('click', onAddBtnClick, false);
    }
    
    function onAddBtnClick(evt)
    {
        let newStr = "<li><input type='checkbox'/></li>";
        document.querySelector('ul').innerHTML += newStr;
    }
        <ul>
            <li><input type='checkbox'/></li>
        </ul>
        <button id='addNewBtn'>添加新项目</button>

    This is an alternative code snippet that adds an item to the end of the list.

    "use strict";
    window.addEventListener('load', onLoaded, false);
    
    function onLoaded(evt)
    {
        document.getElementById('addNewBtn').addEventListener('click', onAddBtnClick2, false);
    }
    
    function onAddBtnClick2(evt)
    {
        let newLi = document.createElement('li');
        newLi.innerHTML = "<input type='checkbox'/>";
        document.querySelector('ul').appendChild(newLi);
    }
        <ul>
            <li><input type='checkbox'/></li>
        </ul>
        <button id='addNewBtn'>添加新项目</button>

    reply
    0
  • Cancelreply