2016年8月17日水曜日

JQuery UI Datepicker を利用する

Webシステムでは日付入力が必要となる場合が多い。
人間が手入力してもよいのだが暦日チェックなどが必要となるため、カレンダーを用いた入力が行われることが多く、JQuery UI Datepicker もそのうちの一つである。

JQuery UI Datepicker を利用する際には、関連する Javascript および CSS を読み込む必要がある。
以下は、JQueryのサイトから直接読み込む方法を採っている。
<html>
<head>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />

<script>
  $(function(){
    $( "#datepicker" ).datepicker();
  });
</script>

</head>
<body>

日付: 
<input type="text" id="datepicker" />

</body>
</html>
デフォルトでは、日付の書式が mm-dd-yyyy となる。日本でよく使用される yy-mm-dd の書式に変更するには、dateFormat オプションを利用する。
<html>
<head>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />

<script>
  $(function(){
    $( "#datepicker" ).datepicker({
        dateFormat: "yy-mm-dd"
        });
  });
</script>

</head>
<body>

日付: 
<input type="text" id="datepicker" />

</body>
</html>
二つの日付入力欄を利用して自至を作成する場合、自側日付は至側日付よりも小さくなるべきである。
このような場合に対応するため、日付の入力制限を行うことができる。
<html>
<head>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css" />

<script>
  $(function(){
    $( "#s_datepicker" ).datepicker({
        dateFormat: "yy-mm-dd",
        onClose: function(selectedDate){
            $( "#e_datepicker" ).datepicker("option", "minDate", selectedDate);}
        });
    $( "#e_datepicker" ).datepicker({
        dateFormat: "yy-mm-dd",
        onClose: function(selectedDate){
            $( "#s_datepicker" ).datepicker("option", "maxDate", selectedDate);}
        });
  });
</script>

</head>
<body>

自: 
<input type="text" id="s_datepicker" />
至: 
<input type="text" id="e_datepicker" />

</body>
</html>

0 件のコメント:

コメントを投稿