If conditon showing alert even when the condition is false

Posted by Adrian on Stack Overflow See other posts from Stack Overflow or by Adrian
Published on 2012-11-22T10:53:44Z Indexed on 2012/11/22 10:59 UTC
Read the original article Hit count: 253

Filed under:
|
|
|

I have problem with if condition. I write a script who should showing alert when value from field #customer-age is less than 21 (the calculated age of person). The problem is - the alert is showing every time - when the value is less and greater than 21.

My html code is:

<div class="type-text">
<label for="birthday">Date1:</label>
<input type="text" size="20" id="birthday" name="birthday" value="" readonly="readonly" />
</div>

<div class="type-text">
<span id="customer-age" readonly="readonly"></span>
</div>

<span id="date_from_start">23/11/2012</span>

and script looks like:

function getAge() {
    var sday =  $('#date_from_start').html();
    var split_date1 = sday.split("/");  
    var todayDate = new Date(split_date1[2],split_date1[1] - 1,split_date1[0]);

    var bday = $('#birthday').val();
    var split_date2 = bday.split("/");
    var birthDate = new Date(split_date2[2],split_date2[1] - 1,split_date2[0]);

    var age = todayDate.getFullYear() - birthDate.getFullYear();
    var m = todayDate.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && todayDate.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}

var startDate = new Date("1935,01,01");

$('#birthday').datepicker({
    dateFormat: 'dd/mm/yy',
    dayNamesMin: ['Nie', 'Pon', 'Wt', 'Sr', 'Czw', 'Pt', 'Sob'],
    dayNames: ['Niedziela','Poniedzialek','Wtorek','Sroda','Czwartek','Piatek','Sobota'],
    monthNamesShort: ['Sty', 'Lut', 'Mar', 'Kwi', 'Maj', 'Cze', 'Lip', 'Sie', 'Wrz', 'Paz', 'Lis', 'Gru'],    
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 1,
    constrainInput: true, firstDay: 1, dateFormat: 'dd/mm/yy',
    yearRange: '-77:-18',
    defaultDate: startDate,
    onSelect: function(dateText, inst) {
        $('#customer-age').html(getAge(new Date(dateText)));
        var cage = $('#customer-age').val();
          if (cage < 21)
             {
             alert('< 21 year');
             }
          else {
          }
    },
    maxDate: +0
});

The workin code you can check on http://jsfiddle.net/amarcinkowski/DmYBt/

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery