form 안의 input value 가져오기 / form input 간편하게 reset 하기

Maria Kim·2021년 10월 17일
0

form 을 잘 다루지 못해 JS로 input 을 다룰 때는
아래처럼 input의 값을 하나하나 불러와 처리하는 것이 편했고 input의 type에 따라 처리도 달리해야 하기 때문에 저렇게 처리하는 게 낫다고 생각했다.

const dEmoji = document.querySelector('input[name="d_emoji"]:checked');
const dEmojiValue = dEmoji ? dEmoji.value : null;
const dInput = document.querySelector('input[name="Dinner"]').value;
const lateNight = document.querySelector('input[name="NightSnack"]').value;
const water = document.querySelectorAll('input[name="w_icon"]:checked')
  .length;

사실 form 안에 처리해야한 값이 언제나 그렇게 많지않아 불편함이 없었던것 같다.

하지만 아래처럼 한방에 form 을 리셋하는 방법을 이번에 알게 되면서
input도 form의 이점을 최대한 살려 form을 기준으로 input을 관리해 보기로 마음먹었다.

와... 모든 input의 value 값을 하나하나 초기화 시키는 작업을 했었는데 한 줄로 정리되다니 너무 멋지지 않은가?! 살짝 지금까지 안쓰고 했던 작업이 노가다였구나 라는 생각이 들며 눈물이 찔끔 날것도 같았지만 이렇게 발전하는 게 아니겠는가 ㅎㅎㅎ ㅜㅡ ㅋㅋㅋㅋ

form을 이용한 1줄 form reset

    const Postform = document.querySelector('#post__form');
    Postform.reset();

그래서 이전의 장황하던 처리방식이

form의 elements + for of 문 + switch 문 => 깔끔! 가독성 ⬆️

역시 사람들은 똑똑하다. 너무 JS를 잘 만들었다. 공부하면 할수록 똑똑한 프로그래밍 언어에 감동한다 😭 그래서 더 많이 공부를 해야겠다 생각한 하루였다. 더똑똑한 개발자가 되는 것이이 나는 물론 모두를 편하게 하는 일이구나를 다시금 느꼈다ㅎㅎㅎㅎ

물론 form 을 통한 input 처리를 하면

  • null을 처리해 줘야 한다면 그 부분을 더 작성해야 한다.(기본값을 미리 설정한다면 그 부분을 편하게 처리할 수 있긴 하다.)
  • 어떤 부분이 빠졌는지, 공통을 처리해야 하는지 생각을 하는 시간을 가져야 하기에 나열식으로 처리할 때보다 더 고민을 해야 할 수 있다.

하지만!!!
마지막 기본값을 사용하고 form을 이용한 식을 보고 난 후 다음부턴 form을 통해 input을 처리하는 방식이 너무 마음에 든다😍

이전 input 처리방식

// Breakfast
const bEmoji = document.querySelector('input[name="b_emoji"]:checked');
const bEmojiValue = bEmoji ? bEmoji.value : null;
const bInput = document.querySelector('input[name="Breakfast"]').value;
// Lunch
const lEmoji = document.querySelector('input[name="l_emoji"]:checked');
const lEmojiValue = lEmoji ? lEmoji.value : null;
const lInput = document.querySelector('input[name="Lunch"]').value;
// Dinner
const dEmoji = document.querySelector('input[name="d_emoji"]:checked');
const dEmojiValue = dEmoji ? dEmoji.value : null;
const dInput = document.querySelector('input[name="Dinner"]').value;
// Others
const lateNight = document.querySelector('input[name="NightSnack"]').value;
const snacks = document.querySelector('input[name="Snacks"]').value;
const drinks = document.querySelector('input[name="Drinks"]').value;
const water = document.querySelectorAll('input[name="w_icon"]:checked').length;
const coffee = document.querySelectorAll('input[name="c_icon"]:checked').length;
const post = {
  bEmoji: bEmojiValue,
  bInput: bInput,
  lEmoji: lEmojiValue,
  lInput: lInput,
  dEmoji: dEmojiValue,
  dInput: dInput,
  lateNight: lateNight,
  snacks: snacks,
  drinks: drinks,
  water: water,
  coffee: coffee,
};

form 을 이용한 input 처리방식(null 처리 x)

const elements = document.querySelector('#post__form').elements;
let post = {};
for (const item of elements) {
  switch (item.type) {
    case 'text':
      post[item.name] = item.value;
      break;
    case 'checkbox':
      if (item.name === 'w_icon' || item.name === 'c_icon') {
          post[item.name] = post[item.name] ? post[item.name] + 1 : 1;
      } else {
          post[item.name] = item.value;
      }
      break;
    default:
      break;
  }
}

form 을 이용한 input 처리방식(null 처리 o)

const elements = document.querySelector('#post__form').elements;
let post = {};
for (const item of elements) {
  switch (item.type) {
    case 'text':
      post[item.name] = item.value;
      break;
    case 'checkbox':
      if (item.name === 'w_icon' || item.name === 'c_icon') {
        if (item.checked === true) {
          post[item.name] = post[item.name] ? post[item.name] + 1 : 1;
        } else {
          post[item.name] = post[item.name] || 0;
        }
      } else {
        if (item.checked === true) {
          post[item.name] = item.value;
        } else if (item.value == 'depressed') {
          post[item.name] = post[item.name] || null;
        }
      }
      break;
    default:
      break;
  }
}

form 을 이용한 input 처리방식(null 처리 o, 기본값 초기에 설정)

const elements = document.querySelector('#post__form').elements;
let post = {
  Breakfast: '',
  Dinner: '',
  Drinks: '',
  Lunch: '',
  NightSnack: '',
  Snacks: '',
  b_emoji: null,
  c_icon: 0,
  d_emoji: null,
  l_emoji: null,
  w_icon: 0,
};
for (const item of elements) {
  switch (item.type) {
    case 'text':
      post[item.name] = item.value;
      break;
    case 'checkbox':
      if (item.name === 'w_icon' || item.name === 'c_icon') {
        if (item.checked === true) {
          post[item.name] = post[item.name] + 1;
        } else {
          post[item.name] = item.value;
        }
        break;
      }
    default:
      break;
  }
}
profile
Frontend Developer, who has business in mind.

0개의 댓글