ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Date Range Picker 소개
    Front/html, css, javascript 2022. 2. 3. 12:23

    개요

    현장실습을 하는 도중 아래와 같이 날짜 범위를 지정하는 input 창을 만들어야 했다.

     

    어떻게 구현을 해야 할지 고민을 많이 했고 두 가지 정도의 아이디어를 떠올렸다.

    1. date 타입 input 태그 2개를 사용하기
      → 디자인 요구 사항을 만족하기 매우 어렵다.
    2. text 타입 input 태그 사용하기
      → 구현 자체는 어렵지 않으나, 백으로 데이터를 전송하고 처리하는 과정이 귀찮고 난잡할 것으로 판단.

     

    사실 담당 멘토님도 2번째 방법을 추천했었지만, 코드가 난잡해질 것이 너무 눈에 보여서 다른 방법을 고민했다.

    그러다가 찾게된 유용한 라이브러리, Date Range Picker를 사용하면 손쉽게 해결할 수 있을 것 같았다. 라이선스도 확인하니 충분히 사내에 활용할 수 있다. (깨알 정보, 멘토님이 라이선스 확인을 꼭 하라고 조언해주셨다)

     

    공식 사이트

    https://www.daterangepicker.com/

     

    Date Range Picker — JavaScript Date & Time Picker Library

    Originally created for reports at Improvely, the Date Range Picker can be attached to any webpage element to pop up two calendars for selecting dates, times, or predefined ranges like "Last 30 Days". To get started, include jQuery, Moment.js and Date Range

    www.daterangepicker.com

     

    본문

    사용법

    공식 문서를 참고하면 충분히 활용할 수 있으므로 자세한 사용법은 생략한다.

     

    어떻게 활용했는가

    나는 다음과 같은 요구사항을 충족시켜야 했다.

    1. 백에서 startDate와 endDate를 보내면 해당 날짜 값을 넣어야 한다.
    2. 저장할 때도 변경되는 사항을 백으로 전달을 해야 한다.

    즉 Date Range Picker에 데이터를 넣기도 해야 하고 보내기도 해야 하는 상황이었는데, 나는 hidden input 2개를 활용하여 해결하였다.

     

    각 hidden input의 value에 백에서 쏴준 날짜 데이터가 있다면 넣어주고, 없다면 오늘 날짜를 넣어준다.

    그런 후 라이브러리 자체에서 startDate: $('input[name="startDate"]').val() 로 값을 할당할 수 있다.

    날짜를 사용자가 변경하면 콜백 함수를 통해 hidden input 값에 삽입하고, submit 할 시 해당 input 값들이 백으로 전송하면 깔끔하게 완성..

     

    코드

    html (백 데이터 부분 네이밍은 임시로 작성)

    <div class="duration">
    	<span>기간</span>
    	<input type="text" name="daterange" value="" />
        <input
          type="hidden"
          name="startDate"
          value="<% if(test.length !== 0) { %>
            <%= test[0].startTest %>
            <% } else { %>
            <%= lastMondayStr %> 
            <% } %>"
        />
        <input
          type="hidden"
          name="endDate"
          value="<% if(test.length !== 0) { %>
            <%= test[0].endTest %>
            <% } else { %>
            <%= lastSundayStr %>
            <% } %>"
        />
    </div>

    js

    $(function () {
          $('input[name="daterange"]').daterangepicker(
            {
              locale: {
                format: "YYYY-MM-DD",
                separator: " ~ ",
                applyLabel: "확인",
                cancelLabel: "취소",
                fromLabel: "From",
                toLabel: "To",
                customRangeLabel: "Custom",
                weekLabel: "W",
                daysOfWeek: ["일", "월", "화", "수", "목", "금", "토"],
                monthNames: [
                  "1월",
                  "2월",
                  "3월",
                  "4월",
                  "5월",
                  "6월",
                  "7월",
                  "8월",
                  "9월",
                  "10월",
                  "11월",
                  "12월",
                ],
              },
              startDate: $('input[name="startDate"]').val(),
              endDate: $('input[name="endDate"]').val(),
              drops: "auto",
            },
            function (start, end, label) {
              $('input[name="startDate"]').val(start.format("YYYY-MM-DD"));
              $('input[name="endDate"]').val(end.format("YYYY-MM-DD"));
              console.log(
                "A new date selection was made: " +
                  start.format("YYYY-MM-DD") +
                  " to " +
                  end.format("YYYY-MM-DD")
              );
            }
          );
        });

     

    참조

    https://wooncloud.tistory.com/26

    'Front > html, css, javascript' 카테고리의 다른 글

    이메일 포맷 검증 방법 (regular expression of email)  (0) 2021.07.03
    ch04. CSS3  (0) 2021.06.25
    ch03. HTML5  (0) 2021.06.24
    ch02. 개발환경 구축  (0) 2021.06.22
    ch01. 웹 프로그래밍 소개  (0) 2021.06.21

    댓글

Copyright@squareyun | Design@black7375