Question

I have a code to check an input value, if it is over 67 years ago.

If the value is over 67, I display a warning.

But this code returns the warning when I just click the input field. How can I prevent it to return true when the input is empty?

$(function(){
    $("#collapse1 #div_id_nested-1-birthdate input").on("change.dp change keyup paste click propertychange", function(e){
            var timediff = moment().diff(moment($(this).val(), "DD/MM/YYYY"), 'years');

            if (timediff  >= 67 ) {
                $('#collapse1 #alert1').remove();
                $('#collapse1 .panel-body').append('<div id="alert1" class="alert alert-warning">You are over 67!</div>');
            } else {
                $('#collapse1 #alert1').remove();
            }
    });

});
Était-ce utile?

La solution

try this check the value is not empty before doing the operation.

$(function(){
        $("#collapse1 #div_id_nested-1-birthdate input").on("change.dp change keyup paste click propertychange", function(e){
                // get the current value and store it in the variable.
                var value = $(this).val();
                // checking the value is not empty
                if(value.length){
                    var timediff = moment().diff(moment(value , "DD/MM/YYYY"), 'years');

                    if (timediff  >= 67 ) {
                        $('#collapse1 #alert1').remove();
                        $('#collapse1 .panel-body').append('<div id="alert1" class="alert alert-warning">You are over 67!</div>');
                    } else {
                        $('#collapse1 #alert1').remove();
                    }
                }

        });

    });
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top