본문 바로가기
Javascript/GMA(2302~)

23.04.18 자바스크립트 참석 명단 리스트 만들기

by hyerin1201 2023. 4. 18.

이름과 전공 값을 입력하고 등록하기 버튼을 누르면

그 밑에 테이블 태그 공간에 값이 출력된다.

 

HTML

<body>
  <div id="container">
    <h1>참가자 명단</h1>
    <form>
      <ul id="userInput">
        <li>
          <label for="name">이 름</label>
          <input type="text" id="name">
        </li>
        <li>
          <label for="major">전 공</label>
          <input type="text" id="major">
        </li>
      </ul>
      <button id="save">등록하기</button>
    </form>
    <table id="userList" border="1">
      <thead>
        <tr>
          <th>이름</th>
          <th>전공</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</body>

 

CSS 스타일

*{
  margin: 0;
  padding: 0;
}
body {
  box-sizing: border-box;
}
#container {
  width: 400px;
  margin: 10px auto;
}
#userInput {
  width: 400px;
  margin: 0 auto;
  margin-left: 20px;
}
h1 {
  margin-bottom: 20px;
}
li {
  list-style: none;
  margin-bottom: 20px;
}
label {
  width: 50px;
  display: inline-block;
  margin-right: 10px;
}
input {
  width: 200px;
  height: 30px;
}
button {
  width: 300px;
  padding: 5px 10px;
  margin-bottom: 20px;
}
table {
  border-collapse:collapse;
  width: 300px;
  text-align: center;
  border: 1px solid #ccc;
}
th, td {
  padding: 5px 10px;
}
td {
  font-size: 0.9em;
  width: 150px;
}

 

Javascript

// 이름, 전공 데이터와 정의값.
// 버튼의 정의
// 버튼을 누르면 출력되는 공간에 대한 정의

let name = document.querySelector("#name");
let major = document.querySelector("#major");
const save = document.querySelector("#save");


save.addEventListener("click",  (e) => { //버튼을 클릭했을 때
  e.preventDefault(); //버튼 태그의 기본 속성값 삭제

  let tbody = document.querySelector("tbody");
  let newTr = document.createElement("tr"); //tr 태그 생성

  let nameTd = document.createElement("td");
  nameTd.innerText = name.value;
  newTr.appendChild(nameTd);

  let majorTd = document.createElement("td");
  majorTd.innerText = major.value;
  newTr.appendChild(majorTd);

  tbody.appendChild(newTr);
  //newTr.innerHTML = `<td>${name.value}</td><td>${major.value}</td>`; //tr태그 안에 들어가는 td태그, 그안의 요소들 
  //tbody.appendChild(newTr); // table 태그의 하위 요소로 넣기

  name.value = ""; // 입력된 후에 인풋박스 값 지우기
  major.value = ""; 
});