Skip to content

Instantly share code, notes, and snippets.

@EncodeTheCode
Created May 13, 2024 06:06
Show Gist options
  • Save EncodeTheCode/e434b3e5a86f76f14ebde171340c63d8 to your computer and use it in GitHub Desktop.
Save EncodeTheCode/e434b3e5a86f76f14ebde171340c63d8 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Delete Boxes</title>
<style>.box { width:100px; height:100px; background-color:lightblue; margin:10px; display:inline-block; text-align:center; line-height:100px; }</style>
</head>
<body>
<select id="boxSelect"></select>
<button onclick="deleteBox()">Delete Box</button>
<button onclick="createNewBox()">Create New Box</button>
<label for="deleteAscending">Ascending Order</label>
<input type="checkbox" id="deleteAscending">
<div id="boxContainer"></div>
<script>
class DataIdGenerator{constructor(){this.counter=1}generateId(){let e=this.counter++,t=this.formatDataId(e);return"data-id-"+t}formatDataId(e){return String(e).padStart(2,"0")}};const dataIdGenerator=new DataIdGenerator;function createBox(e){const t=document.getElementById("boxContainer"),n=document.createElement("div");n.setAttribute("class","box"),n.setAttribute("data-id",e),n.textContent=e,t.appendChild(n);const o=document.getElementById("boxSelect"),a=document.createElement("option");a.value=e,a.textContent=e,o.appendChild(a)}function createNewBox(){let e;do{e=dataIdGenerator.generateId()}while(document.querySelector(`.box[data-id="${e}"]`));createBox(e),reorderDropdown()}for(let e=0;e<10;e++){createNewBox()}function deleteBox(){const e=document.getElementById("boxSelect"),t=document.getElementById("boxContainer"),n=e.value;if(""!==n){const o=document.querySelector(`.box[data-id="${n}"]`);o?(o.parentNode.removeChild(o),e.remove(e.selectedIndex)):alert("Box with specified data-id not found!")}else alert("Please select a box to delete!"),reorderDropdown()}function reorderDropdown(){document.getElementById("boxSelect").selectedIndex=0;const e=document.getElementById("boxSelect"),t=document.getElementById("deleteAscending").checked,n=Array.from(e.options);n.sort((e,o)=>t?e.value.localeCompare(o.value):o.value.localeCompare(e.value)),e.innerHTML="",n.forEach(t=>{e.appendChild(t)})}document.getElementById("deleteAscending").addEventListener("change",()=>{document.getElementById("boxSelect").selectedIndex=0;reorderDropdown()});document.getElementById("boxSelect").selectedIndex=0;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment