Nishant123 Nishant123 - 6 months ago 8
Javascript Question

How to set datepicker on select change?

I have a very simple problem. But I am unable to resolve the issue.

I want to set datepicker to a input on select change. Also on changing the select to other option the datepicker should be removed and only textbox should be displayed.

This is what I have tried so far

jQuery(document).ready(function(){

jQuery('#filevalidity').change(function(){
var option = jQuery(this).find("option:selected").val();
if(option === "MAX_DOWNLOAD_LIMIT")
{

jQuery('#dlorex').next('input').datepicker("destroy");
}
if(option === "EXPIRY_DATE")
{

jQuery('#dlorex').next('input').datepicker({minDate : 1});
}
});

});


Here is the fiddle

Where am I going wrong?

Answer

next() gets the sibling at the same level (in this case, same level as tr)

You can use find() to target the input. Also you have not closed few tags properly.

Here you go:

jQuery(document).ready(function() {

  jQuery('#filevalidity').change(function() {
    var option = jQuery(this).find("option:selected").val();
    if (option === "MAX_DOWNLOAD_LIMIT") {

      jQuery('#dlorex').find("input[name='downlimit']").datepicker("destroy");
    }
    if (option === "EXPIRY_DATE") {

      jQuery('#dlorex').find("input[name='downlimit']").datepicker({
        minDate: 1
      });
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div id="general">
  <table width="100%">

    <tr>
      <td>File Validity:</td>
      <td>
        <select name="filevalidity" id="filevalidity">
          <option value="MAX_DOWNLOAD_LIMIT">Download Limit</option>
          <option value="EXPIRY_DATE">Expiry Date</option>
        </select>
      </td>
    </tr>
    <tr id="dlorex">
      <td>
        <label>Download Limit</label>
      </td>
      <td>
        <input type="text" name="downlimit" />
      </td>
    </tr>

  </table>
</div>

Fiddle: http://jsfiddle.net/ktjsyfg0/4/