1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【jQuery UI Datepicker】日付プルダウンとカレンダーアイコンを連動させる

Last updated at Posted at 2019-03-03

#経緯
jQueryのDatepickerをいじって、ふと思った。
「テキストボックス+アイコン」はあるけど「プルダウン+アイコン」がない。
ググってもなかったんだ。
あったら教えてください。ごめんなさいします。

#コード
yyyy/mm/ddフォーマットで当日から3か月分の表示を想定

index.html
<select id="ymd_pulldown" size="1"></select>
<input type="hidden" id="datepicker">

<!-- JSさんたち -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/i18n/jquery.ui.datepicker-ja.min.js"></script>
<script src="/script.js" defer></script>
script.js
$(document).ready(function(){
  setDayPulldown();
  
  function setDayPulldown(){
    let current = new Date();
    let date
    let year_val = current.getFullYear();
    let month_val = current.getMonth() + 1;
    let day_val = current.getDate();
    current.setDate(current.getDate() + 1);

    for (let i = 0; i < 90; i++) {
      date = new Date(year_val, month_val - 1, day_val + i);
      $('#ymd_pulldown').append('<option value="' + getDayStr(date) + '">' + getDayStr(date) + '</option>');
    }
    $('#ymd_pulldown').append('</select>');
  }

  function getDayStr(date){
    let yy = date.getFullYear();
    let mm = ("0" + (date.getMonth() + 1)).slice(-2);
    let dd = ("0" + date.getDate()).slice(-2);
    return yy + '/' + mm + '/' + dd;
  }
  
  $( "#datepicker" ).datepicker({
    showOn: "button",
    buttonImage: "[画像のパス]",
    buttonImageOnly: true,
    buttonText: "Select date",
    minDate: "d",
    maxDate: "+3m",
    altField:"#ymd_pulldown",
    dateFormat: "yy/mm/dd"
  });

  // プルダウンで選択時、カレンダーにも値を連動
  $('#ymd_pulldown').change(function() {
    $('#datepicker').val($('#ymd_pulldown').val());
  });
});

#結果
こんな感じ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?