开发者

Button onclick only checkes the first appended checkbox

开发者 https://www.devze.com 2023-01-27 21:53 出处:网络
With the script below I append 3 elements when the append button is clicked. a checkbox input text field

With the script below I append 3 elements when the append button is clicked.

  • a checkbox
  • input text field
  • delete button

For now, when the delete button is clicked the checkbox is checked, but when I append another (let's call it a group) three items, the script doesn't work.

Can anybody explain how I can link the elements in some sort of way. So that every time I click the append button the elements are linked to the elements that were created at the same time the same on click.

Thank you so much in advance

   <html>
   <head>
   <script language="Javascript">

     function append()
     {
    var cb = document.createElement("input");
    cb.type = "checkbox";
    cb.id = "id"
            cb.checked = false;

    var textfield = document.开发者_高级运维createElement("input");
    var delbtn = document.createElement("input");
    delbtn.type = "button";
    delbtn.value = "remove";
    delbtn.onclick= function(){remove()}

    document.getElementById('append').appendChild(cb);
    document.getElementById('append').appendChild(textfield);
    document.getElementById('append').appendChild(delbtn);
  }


 function remove()
 {
    id.checked = true;      
 }
   </script>
   </head>
   <body>
      <div id="append"></div>
      <input type="button" value="append" onClick="javascript:append()"/>
   </body>
</html>


Each time you append a new checkbox, you're running

cb.id = "id"

This is problematic, since elements should have unique ids.

Also, you're referencing the element by its id in the global scope:

id.checked = true;

You should use the standard document.getElementById() instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消