- SPLessons

jquery ui datepicker set default date

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

jquery ui datepicker set default date

jquery ui datepicker set default date

Hi every one yesterday we got a requirement that we need to set the default date based on the value in input element. If you have only one date picker then we can set with single line code but if you have more date picker in your form then here is very simple soution  Eg:

<input name='test1' class="questionDate" type="text" value=" 05/16/2015 " /></pre>
<pre><input name='test2' class="questionDate" type="text" value=" 04/13/2015 " /></pre>
<pre><input name='test3' class="questionDate" type="text" value=" 07/02/2015 " /></pre>
<pre><input name='test4' class="questionDate" type="text" value=" 05/16/2014 " /></pre>
<pre><input name='test5' class="questionDate" type="text" value=" 10/15/2015 " />

Quick Solution

$(function() {
        $("input.questionDate").datepicker({
            dateFormat: 'mm/dd/yy'
              });

        $("input.questionDate").each(function(){
            var currentValue = $(this).val();
            if(currentValue)
                $(this).datepicker('setDate',new Date(currentValue));
        });
   });

Steps

  • If you see the line number 2 in above code there we have initialized the jQuery UI date picker.
  • Line number 6 here our main logic will goes here.
  • “$(‘input.questionDate’).each(function(){})” this line of code will iterate over all input elements with class “.questionDate”.
  • Then we will get the input value into ” var currentValue “
  • Then we have checked does it have value or not.
  • If it has a value then set the default value of each date picker element with “datepicker(‘setDate’, ”)” function.

Project Structure


+ index.html
+ script.js

script.js


$(function() {
       $("input.questionDate").datepicker({
            dateFormat: 'mm/dd/yy'
        });

        $("input.questionDate").each(function(){
            var currentValue = $(this).val();
            if(currentValue)
                $(this).datepicker('setDate',new Date(currentValue));

        });
        $("input.questionDate").keydown(function(event) {
            if(event.keyCode != 8){
                event.preventDefault();
            }
        });

});

index.html


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SPLessons</title>
<link rel='stylesheet' type='text/css' href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css" type="text/css"> 
</head>

<body>

Start Date: <input class="questionDate" value=" 05/16/2015 "><br>
End Date: <input class="questionDate" value=" 05/31/2015 "><br>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"> </script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.1/jquery-ui.min.js"> </script>
<script type="text/javascript" src="script.js"> </script>

</body>
</html>


Demo