Lami
삶이 온통 사람의 길이니
Lami
전체 방문자
오늘
어제
  • 분류 전체보기 (165)
    • Elice (1)
      • 회고록 (1)
    • Git (0)
    • HTML ▪ CSS (4)
    • JavaScript (7)
      • BOJ (2)
      • Programmers (0)
      • Study Note (5)
    • TypeScript (0)
    • React (21)
      • Lecture (19)
      • Study Note (2)
    • Python (44)
      • CodeUp (38)
      • Programmers (0)
      • Study Note (6)
    • Modern Agile (80)
      • Tech Talk (7)
      • TIL (73)
    • 문제해결 (1)
    • 회고록 (5)
    • 도란도란 (2)

블로그 메뉴

  • Github

공지사항

  • 👋 안녕하세요!

인기 글

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
Lami

삶이 온통 사람의 길이니

Day 12 - 2021.12.21
Modern Agile/TIL

Day 12 - 2021.12.21

2021. 12. 21. 16:26

과제 - 개발 과제(Select Box와 Check Box)

Select Box

https://github.com/ohchanghoon/wooahan-agile-frontend-task-3term/issues/2

Check Box

https://github.com/ohchanghoon/wooahan-agile-frontend-task-3term/issues/3

"HTML 구조"와 "API 명세"를 이해하고 selectbox.js, checkbox.js 를 완성해야한다.

selectbox.js

https://github.com/ohchanghoon/wooahan-agile-frontend-task-3term/pull/9/commits/4ede8d2921fdf4ca4e5360f631fd99100493e646

'use strict';

const selectPurpose = () => {
  let selectOption = document.querySelector('select');
  selectOption = selectOption.options[selectOption.selectedIndex].value;
  return selectOption; // 선택한 selectbox가 무엇인지 return
};

const changeResult = (data) => {
  document.querySelector('#result').innerHTML = data ? '정답' : '오답';
}; // API를 사용하고 그 결과가 true면 정답을, false면 오답을 기재

function getResult(selectOption) {
  const data = {
    answer: selectOption,
  };  // answer는 선택한 selectbox 값인데 API 명세서대로 객체 형태로 저장해서 사용
  const request = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify(data),  // JSON을 문자열로 바꿔주는 코드
  };

  fetch('/api/selectbox/submit', request)
    .then((res) => res.json())  // 문자열로 있는 JSON을 다시 JSON으로 바꿔줌
    .then((data) => changeResult(data));  // 그 JSON으로 바뀐 데이터로 화면에 결과를 기재하는 함수 실행
}

document.getElementById('submit-btn').addEventListener('click', () => {
  const value = selectPurpose(); // 버튼을 클릭할 때마다 어떤 값을 선택했는지 value에 저장
  getResult(value); // value로 API 사용
});

화면에 결과는 잘 나오는데 fetch를 제대로 사용한 게 아닌 것 같아서 멘토님한테 질문해서 봐주신 코드.

 

 

checkbox.js

https://github.com/ohchanghoon/wooahan-agile-frontend-task-3term/pull/18/commits/b94db8f757aa70ec047cc2cf5bba4c8b23fb845c

'use strict';

let getChecked = () => {
  const query = 'input[type="checkbox"]:checked';
  const selectedEls = document.querySelectorAll(query);
  let check = [];

  selectedEls.forEach((el) => {
    check.push(el.value);
  });
  return check; // 체크한 값을 배열로 넣어서 return
};

function getResult(check) {
  const data = {
    answers: check,
  };
  const request = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json; charset=utf-8',
    },
    body: JSON.stringify(data),
  };

  fetch('/api/checkbox/submit', request)
    .then((res) => res.json())
    .then((data) => changeResult(data));
}

function changeResult(data) {
  document.querySelector('#result').innerHTML = data ? '정답' : '오답';
} // API와 비교 후 true면 정답을, false면 오답을 기재

document.querySelector('#submit_btn').addEventListener('click', () => {
  const value = getChecked();
  getResult(value);
});

이번에는 멘토님 도움 없이 풀었다. 하지만 selectbox에서 작성했던 코드들을 비교해가며 리팩토링했던 거라 온전히 내 코드라고는 할 수 없다😢

 


TIL

  • html에서 원하는 곳에 id를 주고 주소창에서 해당 페이지 뒤에 #id이름을 넣으면 그 id가 있는 곳이 보여진다. (북마크한 것처럼)
  • select box에서 선택한 옵션의 text 값 가져오기
let target = document.getElementById("testSelect");
target.options[target.selectedIndex].text;
  • select box에서 선택한 옵션의 text 값 가져오기
let target = document.getElementById("testSelect");
target.options[target.selectedIndex].value;
  • Ajax와 fetch
    • https://www.daleseo.com/js-window-fetch/
    • https://codingbroker.tistory.com/62
  • API 명세서에 나와있는 형태대로 작성해야 한다!
  • 함수는 한 가지 기능만!
  • 만약 다른 기능도 사용할 것 같으면 그런 기능의 함수를 따로 만들고 결과를 return해서 그 값을 사용할 수 있게 하기!
  • 멘토님이 해주신 코드는 리팩토링한 코드. 처음에는 코드가 더러운 게 정상. 실행이 잘 된다면 그때 코드를 리팩토링한다.
  • checkbox
    • https://hianna.tistory.com/430

'Modern Agile > TIL' 카테고리의 다른 글

Day 14 - 2021.12.23  (0) 2021.12.24
Day 13 - 2021.12.22  (0) 2021.12.22
Day 11 - 2021.12.20  (0) 2021.12.20
Day 10 - 2021.12.17  (0) 2021.12.17
Day 09 Tech Talk Day🎤 - 2021.12.16  (0) 2021.12.16
    'Modern Agile/TIL' 카테고리의 다른 글
    • Day 14 - 2021.12.23
    • Day 13 - 2021.12.22
    • Day 11 - 2021.12.20
    • Day 10 - 2021.12.17
    Lami
    Lami
    성장하는 즐거움을 알아가는 중입니다🌱

    티스토리툴바