Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to check if a date input field in empty

Tags:

jquery

What I have right now.

$('form input[name="birthDate"])').blur(function () {
      var dob = $("#dob").val();
      if(dob == "") {
        $("#dobAlert").show();
        $("#laba").attr("disabled", true);
      } else {
        $("#dobAlert").hide();
      }
    });

The #laba is a button that I want to disable if the input is empty. I know I can disable the button if I put required in the input tag. But the problem I have is that it doesn't show the alert.

Code here

like image 876
karateka11 Avatar asked Aug 13 '14 20:08

karateka11


Video Answer


1 Answers

Inputs of type date won't return empty, because there will be the date placeholder there (dd/mm/yyyy). You can test if the value is a valid date.

First, fix your jQuery selector, because there's an extra bracket there. Also use .prop() instead of .attr() to toggle the disabled property.

$('input[name="birthDate"]').blur(function () {
    var dob = $("#dob").val();

    if (!Date.parse(dob)) {
        $("#dobAlert").show();
        $("#laba").prop("disabled", true);
    } else {
        $("#dobAlert").hide();
    }
});

Demo

Another way is to check for the Falsy like @Callebe suggested:

$('input[name="birthDate"]').blur(function () {
    if (!$("#dob").val()) {
        $("#dobAlert").show();
        $("#laba").prop("disabled", true);
    } else {
        $("#dobAlert").hide();
    }
});

Demo

like image 68
melancia Avatar answered Oct 03 '22 07:10

melancia