Home>

Get the value of an input element, and enable/disable another input depending on the length of that value

What I did
<form>
  <input type = "text" name = "old_date">
  <input type = "text" name = "new_date">
</form>
<script>
$(function () {
  var $new = $('. new_date');
  $new.on ('focus', function () {
    $(". old_date"). prop ('disabled', true);
  });
  $new.on ('blur', function () {
    console.log ("new_date blur");
    var newvalue = $new.val ();
    console.log (newvalue);
    if (newvalue.length>0) {
        // If new_date has been entered
        $(". old_date"). prop ('disabled', true);
    } else {
        // If new_date is not entered
        $(". old_date"). prop ('disabled', false);
    }
  });
});
</script>
Problems/questions

How can I get the value of new_date?
How can I determine if a new_date value exists?

  • Answer # 1

    Answer that you are using jQuery UI Datepicker.
    It seems that theblurevent is fired "just after selecting a date from the calendar by clicking (= blur)" and "just before a date is input to the input element".
    Therefore, it is considered that the value ($new.val ()) output byconsole.log ()remains the old input value.
    One solution would be to use Datepicker'sonCloseoption instead of picking up theblurevent.

    $(function () {
      var $new = $('. new_date');
      $new.on ('focus', function () {
        $(". old_date"). prop ('disabled', true);
      });
      // ↓ Change only one line
      $new.datepicker ('option', 'onClose', function () {
        // omitted
      });
    });

    Sample code
    (Fork the spookybird code in the request to correct the question.)