简体   繁体   中英

Javascript - get date from field and calculate date of birth

I have a field with a datepicker which is used on a date of birth text field. I have also got an age text input which I would like to populate with their age upon the date of birth field information being entered (so it would compare against the current date and show the childs age)

I'm having a little bit of trouble creating the correct date format (dd-mm-yyyy) in JavaScript. So far I have this.

HTML:

<label for="child_age">Age</label>
<p><input type="text" class="child_age" name="child_age" /></p>

<label for="child_dob">Date of Birth</label>
<p><input type="text" class="child_dob" name="child_dob" /></p>

JQUERY:

$(function () {
$(".child_dob").change(function(event){
        console.log();
        var d = new Date();
        var dob = $(this).val();
        console.log(dob); //shows the correct date from the datepicker (dd-mm-yyyy)
        console.log(d); //shows Tue Apr 30 2013 16:48:32 GMT+0100 (GMT Daylight Time) 
    });
});

How would I convert the date into the correct format and compare it against the information entered in the child_dob field?

To get the date selected in the datepicker, use the getDate method:

$(function () {
    $(".child_dob").change(function(event){
        console.log();
        var d = new Date();
        var dob = $(this).datepicker("getDate");
        console.log(dob);
        console.log(d);
    });
});

It might be better to put this code in the onSelect option of the datepicker rather than the change event of the form field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM