방명록
- [개발자의품격][부트캠프][1기][12차시] JavaScript 주요 포인트 #16 | DOM 패턴 - 조회, 삭제2022년 02월 21일 19시 32분 38초에 업로드 된 글입니다.작성자: DandyNow728x90반응형
JavaScript 주요 포인트 #16
json 샘플 데이터를 생성해주는 사이트를 이용해 실습에 사용될 db.json 파일을 준비한다.
JSON GENERATOR: https://json-generator.com/
조회
조회 1
<!-- dom.html --> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> .normal-table { border: 1px solid black; border-collapse: collapse; width: 100%; } .normal-table th, .normal-table td { border: 1px solid black; padding: 5px 10px; } .normal-table thead tr { background-color: yellow; } .striped tbody tr:nth-child(odd) { background-color: grey; } .hover tbody tr:hover { background-color: yellow; } </style> </head> <body> <button onclick="doSearch();">조회</button> <table class="normal-table striped"> <thead> <tr> <th>Name</th> <th>Company</th> <th>Gender</th> <th>Email</th> <th>Phone</th> <th>Addres</th> </tr> </thead> <tbody id="tbBody"></tbody> </table> <script> async function doSearch() { const res = await fetch("http://localhost:3000/customers"); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push(`<td>${item.name}</td>`); // td(table data) h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } </script> </body>
조회 2
<!-- dom.html --> <body> <!-- select박스 --> <select name="" id="gender"> <option value="">전체</option> <option value="male">남자</option> <option value="female">여자</option> </select> <button onclick="doSearch();">조회</button> <table class="normal-table striped"> <thead> <tr> <th>Name</th> <th>Company</th> <th>Gender</th> <th>Email</th> <th>Phone</th> <th>Addres</th> </tr> </thead> <tbody id="tbBody"></tbody> </table> <script> async function doSearch() { const gender = document.querySelector("#gender").value; // 전체, 남, 여 select박스 선택 조회 기능 if (gender === "") { const res = await fetch("http://localhost:3000/customers"); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } else { const res = await fetch( `http://localhost:3000/customers?gender=${gender}` ); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push(`<td>${item.name}</td>`); // td(table data) h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } </script> </body>
반복적인 코드 정리
<!-- dom.html --> <script> // 반복적인 코드를 정리함 async function doSearch() { const gender = document.querySelector("#gender").value; let resource = "http://localhost:3000/customers"; if (gender !== "") { resource = `http://localhost:3000/customers?gender=${gender}`; } const res = await fetch(resource); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push(`<td>${item.name}</td>`); // td(table data) h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } </script>
조회 3
<!-- dom.html --> <body> <select name="" id="gender"> <option value="">전체</option> <option value="male">남자</option> <option value="female">여자</option> </select> <!-- 이름 검색용 input --> <!-- onkeyup은 이름 검색시 엔터 입력 여부를 체크 --> <input type="search" name="" id="name" placeholder="Name" onkeyup="checkEnter(event);" /> <button onclick="doSearch();">조회</button> <table class="normal-table striped"> <thead> <tr> <th>Name</th> <th>Company</th> <th>Gender</th> <th>Email</th> <th>Phone</th> <th>Addres</th> </tr> </thead> <tbody id="tbBody"></tbody> </table> <script> async function doSearch() { const gender = document.querySelector("#gender").value; const name = document.querySelector("#name").value; // 이름 검색 let resource = "http://localhost:3000/customers"; // like 검색 적용. 값의 일부로 검색함. if (gender === "") { if (name !== "") { resource = `http://localhost:3000/customers?name_like=${name}`; } } else { if (name === "") { resource = `http://localhost:3000/customers?gender=${gender}`; } else { resource = `http://localhost:3000/customers?gender=${gender}&name_like=${name}`; } } const res = await fetch(resource); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push(`<td>${item.name}</td>`); // td(table data) h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } // 이름 검색시 엔터키 입력으로 조회 function checkEnter(e) { // console.log(e); if (e.keyCode === 13) { doSearch(); } } </script> </body>
삭제
<!-- dom.html --> <body> <select name="" id="gender"> <option value="">전체</option> <option value="male">남자</option> <option value="female">여자</option> </select> <input type="search" name="" id="name" placeholder="Name" onkeyup="checkEnter(event);" /> <button onclick="doSearch();">조회</button> <!-- 체크박스 체크된 경우에만 버튼 활성화 --> <button onclick="doDelete();" id="btnDelete" disabled>삭제</button> <table class="normal-table striped"> <thead> <tr> <!-- 체크하면 데이터 전체 선택/해제 --> <th><input type="checkbox" id="chks" onchange="checkAll()" /></th> <th>Name</th> <th>Company</th> <th>Gender</th> <th>Email</th> <th>Phone</th> <th>Addres</th> </tr> </thead> <tbody id="tbBody"></tbody> </table> <script> async function doSearch() { const gender = document.querySelector("#gender").value; const name = document.querySelector("#name").value; let resource = "http://localhost:3000/customers"; if (gender === "") { if (name !== "") { resource = `http://localhost:3000/customers?name_like=${name}`; } } else { if (name === "") { resource = `http://localhost:3000/customers?gender=${gender}`; } else { resource = `http://localhost:3000/customers?gender=${gender}&name_like=${name}`; } } const res = await fetch(resource); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push( `<td><input type="checkbox" value="${item.id}" name="chk" onchange="isChecked();" /></td>` ); h.push(`<td>${item.name}</td>`); // td(table data) h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } function checkEnter(e) { // console.log(e); if (e.keyCode === 13) { doSearch(); } } // 선택 삭제 async function doDelete() { const chks = document.querySelectorAll("[name=chk]:checked"); // 체크박스가 1개 이상 선택되었을 경우 삭제 if (chks.length > 0) { if (confirm("정말 삭제하시겠습니까?")) { for (const chk of chks) { // id 값으로 삭제함 await fetch(`http://localhost:3000/customers/${chk.value}`, { method: "DELETE", }); } alert("데이터가 정상작으로 삭제 되었습니다."); doSearch(); // json-sever에서는 작동하지 않았다! } } else { alert("삭제할 아이템을 선택하세요."); } } // 체크하면 전체 선택/해제 function checkAll() { const checkValue = document.querySelector("#chks").checked; const chks = document.querySelectorAll("[name=chk]"); for (const chk of chks) { chk.checked = checkValue; } isChecked(); } // 체크박스 체크 여부에 따라 삭제 버튼 활성/비활성 function isChecked() { const chks = document.querySelectorAll("[name=chk]:checked"); if (chks.length > 0) { document.querySelector("#btnDelete").disabled = false; } else { document.querySelector("#btnDelete").disabled = true; } } </script> </body>
최종코드
<!-- dom.html --> <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <style> .normal-table { border: 1px solid black; border-collapse: collapse; width: 100%; } .normal-table th, .normal-table td { border: 1px solid black; padding: 5px 10px; } .normal-table thead tr { background-color: yellow; } .striped tbody tr:nth-child(odd) { background-color: grey; } .hover tbody tr:hover { background-color: yellow; } </style> <body> <select name="" id="gender"> <option value="">전체</option> <option value="male">남자</option> <option value="female">여자</option> </select> <input type="search" name="" id="name" placeholder="Name" onkeyup="checkEnter(event);" /> <button onclick="doSearch();">조회</button> <button onclick="goToCreate();">생성</button> <button onclick="doDelete();" id="btnDelete" disabled>삭제</button> <table class="normal-table striped"> <thead> <tr> <th><input type="checkbox" id="chks" onchange="checkAll()" /></th> <th>Name</th> <th>Company</th> <th>Gender</th> <th>Email</th> <th>Phone</th> <th>Addres</th> </tr> </thead> <tbody id="tbBody"></tbody> </table> <script> async function doSearch() { const gender = document.querySelector("#gender").value; const name = document.querySelector("#name").value; let resource = "http://localhost:3000/customers"; if (gender === "") { if (name !== "") { resource = `http://localhost:3000/customers?name_like=${name}`; } } else { if (name === "") { resource = `http://localhost:3000/customers?gender=${gender}`; } else { resource = `http://localhost:3000/customers?gender=${gender}&name_like=${name}`; } } const res = await fetch(resource); const resJson = await res.json(); console.log(resJson); renderTable(resJson); } function renderTable(data) { const h = []; for (const item of data) { h.push("<tr>"); h.push( `<td><input type="checkbox" value="${item.id}" name="chk" onchange="isChecked();" /></td>` ); h.push(`<td>${item.name}</td>`); h.push(`<td>${item.company}</td>`); h.push(`<td>${item.gender}</td>`); h.push(`<td>${item.email}</td>`); h.push(`<td>${item.phone}</td>`); h.push(`<td>${item.address}</td>`); h.push("</tr>"); } document.querySelector("#tbBody").innerHTML = h.join(""); } async function doDelete() { const chks = document.querySelectorAll("[name=chk]:checked"); if (chks.length > 0) { if (confirm("정말 삭제하시겠습니까?")) { for (const chk of chks) { await fetch(`http://localhost:3000/customers/${chk.value}`, { method: "DELETE", }); } alert("데이터가 정상작으로 삭제 되었습니다."); doSearch(); } } else { alert("삭제할 아이템을 선택하세요."); } } function checkAll() { const checkValue = document.querySelector("#chks").checked; const chks = document.querySelectorAll("[name=chk]"); for (const chk of chks) { chk.checked = checkValue; } isChecked(); } function isChecked() { const chks = document.querySelectorAll("[name=chk]:checked"); if (chks.length > 0) { document.querySelector("#btnDelete").disabled = false; } else { document.querySelector("#btnDelete").disabled = true; } } function checkEnter(e) { // console.log(e); if (e.keyCode === 13) { doSearch(); } } function goToCreate() { document.location.href = "dom_create.html"; } </script> </body> </html>
728x90반응형'영광의 시대! > 2022 개발자의 품격 부트캠프 1기' 카테고리의 다른 글
다음글이 없습니다.이전글이 없습니다.댓글