How to calculate age from given data on input field? - javascript

I have searched but i didn't get perfect solution of my issue.I can calculate age in normal way.But i haven't any idea how can i calculate age from given data on input field.I have used jQuery DatePicker for input field.My code:
$birthday = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $birthday ->diff($to)->y.' Years, '.$birthday ->diff($to)->m.' Months, '.$birthday ->diff($to)->d.' Days ';
This is my field:
Now i want $birthday will be dynamic and it will insert and want to show immediately age calculation without page load. Have any clue? Thanks in advance.

The jQuery datepicker displays the dates in an input field with id="datepicker" that you can use to get your date. For a client-side calculation, the momentjs library mentionned in other answer if perfect for this job.
fromdate = $('#datepicker').val();
console.log(fromdate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="datepicker" class="hasDatepicker" value="2016/14/12">
If you want to calculate server-side, you can pass the value to PHP without reloading page with Ajax:
$('#datepicker').change(function(){
$.ajax({
type: "POST",
url: "datecalc.php",
data: {text:$(this).val()}
});
});

If you want to calculate the age in jQuery, you can use moment.js like this:
moment("05/05/1998", "MM/DD/YYYY").month(0).from(moment().month(0));
// Output = 22 years ago
$(function() {
var dob = $('.dob').val();
$('.dob').on('input', function(e) {
var a = moment($(this).val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
});
var a = moment($('.dob').val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='dob' type='text' value="05/05/1996">
Inside your controller, you can use Carbon's age method like this:
$birthday = Carbon\Carbon::parse('1970-02-01');
$age = $birthday->age;
// Output - (int) 46
See Carbon Docs for reference
Hope this helps!

You need to read the value of the data input field using JQuery or Javascript and then pass the value to your age calculation function.
For example if your date field has id="date-picker", then you can read the date as $("date-picker").val() or document.getElementById("date-picker").value()

Related

Checking difference between two date and display custom message

Hello I have input on registration form and want to retrieve the value of input and compare it with the current date using JavaScript and display message after check age if age less than 18 year and display custom message on the bottom of input.
var dateControl = document.querySelector('input[type="date"]').getFullYear();
var startDate = new Date(document.getElementById('date1').value);
and this is the HTML
<input type="date" name="date" class="form-control" id="date1" value="{{ old('date', date('Y-m-d')) }} " onclick="checkDate()">
<div id="currentdate"></div>
but is give old value after each click.
and the message not displayed
Best regards
Not much code to go from but I think you may need this function anyway to compare the date you receive from the form with the current date and get the difference
function process() {
var today = new Date();
var date = new Date(document.getElementById("date1").value);
var diff = Number((today.getTime() - date.getTime()) / 31536000000).toFixed(0);
if (diff >= 18) {
// Your form submission goes here
console.log("success");
} else {
// your error handeling goes here
console.log("error");
}
}
PS: That this method won't give you the difference in an exact way,
it will just give you the difference between the years.

Unable to access input date values with javascript

I've been using forms which upon submit call a function which makes use of the inputted data. So far this has worked fine with text, but switching to date inputs is causing me trouble.
I'm using the following code, but the "startDate", "endDate" values are empty.
<form onsubmit="myFunction()">
Start Date:
<input type="date" name="startDate" id="startDate">
End Date:
<input type="date" name="endDate" id="endDate">
<input type="submit">
</form>
<!-- Form to process above date submit -->
<script>
function myFunction() {
var locationID = "1";
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var apiURL = "APIUrl" + locationID + "_" + startDate + "_" + endDate;
alert("The form was submitted" + apiURL);
$.get(apiURL, function( data ) {
$( ".result" ).html( data );
});
}
</script>
The alert gives me back the APIUrl, plus the location ID, but blank values for the dates.
Any ideas?
Thanks for your help.
You didn't specify what browser you are using.
Since you're already using jQuery, I recommend using it to retrieve the field values, i.e.
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
That would resolve browser inconsistencies that could play a part in your issue.
Your code work as expected in Chrome because it supports input date but this is not the case for IE, Firefox and Safari as you can see here : http://caniuse.com/#search=input%20date
It would probably be better if you use a library like JQuery-UI for the datepicker so it can be supported by all browsers

Date of Birth Check using angular

I am new to angular and I am not sure how to work with dates. I have a form with name and date of birth.
Before submission I want to check if the person is older than 18 and show an error message before the form is submitted.
But I donot have access to the dob variable in the form unless it is submitted. In my code I have access to $scope.contact.dob only inside addContact(),( after the date is submitted). How do I do date of birth validations before form submission?
My code snippet is shown below
<form>
<input ng-model="contact.name">
<input ng-model="contact.dob" ng-min="minAge()">
<p ng-show="userForm.birthday.$error.min">Mustatleast 18.</p>
<button ng-click=addContact()></button>
</form>
my controller:
.controller("myctrl", function($scope){
$scope.addContact = fucntion(){
console.log($scope.contact)
$scope.contact.dob
}
$scope.minAge = function () {
var current = new Date();
var minYear = current.getFullYear() - 100;
var min = new Date(minYear,current.getMonth(),current.getDate()).toISOString();
return min;
};
})
In angular, while there is a directive for ng-minlength, there is no built-in-directive ng-min. Take a look at the documentation here.
https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D
Instead of ng-min, use the HTML min attribute.
Your code should look like this
<input ng-model="contact.dob" min="{{minAge()}}">
As for the error messages, you should take a look at ng-messages.

jquery filter comparing dates

I'm currently trying to create a filter that will allow me to select a date using jQueryUI datepicker. This date will then be compared to the value of a hidden input. The parent div of the hidden input will then be hidden using .hide() function if the hidden date is less than the date select using the picker.
<div data-value="I0001-APP0277-S" class="server_wrapper" style="display: block;">
<div class="detail_wrapper">....</div>
<input type="hidden" class="buildStart_hidden" value="4/25/2014 1:46:19 pm">
</div>
<input type="text" id="buildStart_filter" class="secondary_live_filter hasDatepicker">
Using this code:
$('#buildStart_filter').change(function(){
var date = $(this).val();
$('.buildStart_hidden').each(function(){
if(date>$(this).val().split(' ')[0]){
$(this).parent().hide();
}
});
});
But using this code doesn't work. I think it may be due to the comparison of string values rather than date values. What can I change to make the comparison work?
Maybe:
You missing to remove the hour from DATE
date.split(' ')[0] > $(this).val().split(' ')[0]
After some more work I have figured out the problem.
I was trying to compare string types and not Date types.
This code is working now as hiddenDate and FilterDate are Date() types and thus can be evaluated using >= operator:
$('#buildStart_filter').change(function(){
var filterDate = $('#buildStart_filter').datepicker('getDate');
$('.buildStart_hidden').each(function(){
var hiddenDateStr = $(this).val();
var hiddenDate = new Date(hiddenDateStr);
if(filterDate>=hiddenDate){
$(this).parent().hide();
}else{
$(this).parent().show();
}
});
});

How to save Date & Time in Parse.com using Javascript

I am trying to get the Date and Time from the user and want to submit it to Parse.com. But when I am facing the problem with the following code
What mistake am I doing here?
<div id="main">
<form name="myForm" action="" method="get">
Date: <input type="datetime-local" name="datentime" id="theDate">
<input type="submit" value="Submit" onclick="myFunction()">
</form>
and the javascript code
function myFunction()
{
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
var date = new Date();
date = document.getElementById("theDate").value; //document.forms["myForm"] ["datentime"].value; /*new Date();*/
testObject.set("myDate", date);
testObject.save(null, {
success: function(testObject) {
$(".success").show();
},
error: function(testObject, error) {
$(".error").show();
}
});
}
In above line testObject.set("myDate", date); this like is not working.I am not sure how to take the input from the date and give it to the parse.com
where the column name is myDate of type Date
If I try testObject.set("foo","testing...") where foo is column name of type string.It's working properly
Your issue is just with the way that you are creating a date. I would think that it should work, but is it possible that it is creating a string object?
try checking the type of date it should show an object, if it does not, then the date is not a date, but just a string:
console.log(typeof(date));
Also try to log the value:
console.log(document.getElementById("theDate").value);

Categories

Resources