I'm working on a project using a PHP framework and AJAX -JQUERY, but I'm facing a difficult situation, I usually know how to make a dropdown menu depend to another, but now i need a dropdown menu that contains the age ranges that's depend on the date typed in birth-date field, I would like that when I type in the birth-date field, the drop-down menu should automatically select the age range, but if the date field is empty it must select the "unspecified" option whose ID equals 4 which appears in the DATE_RANGE table, Please help me to solve this riddle, welcome to any suggestion. If I made a mistake in the question asked, please explain to me what should I do, any help will be appreciated
//More Details:
I have a table named Human which contains (ID, FULL_NAME, BIRTH_DATE, AGE_RANGE_ID), and a Table named AGERANGE which in turn contains (ID, RANGE_NAME), the brings back the age Ranges stored in the AGERANGE table The age groups in the table:
here is my code
<div >
<label for="birth-date" >BIRTH DATE</label>
<input type="text" name="birth-date" id="birth-date" value="<?php echo set_value('BIRTH_DATE', $row->BIRTH_DATE); ?>" >
<label for="date_range" >AGE RANGE</label>
<select name="date_range" id="date_range">
<option></option>
<?php
foreach ($date_ranges as $row) {
echo '<option value="' . $row->CODE . '"' . set_select('DATE_RANGE', $row->CODE, $row->CODE === $row->TYPE_REPRESENTANT_CODE) . '>' . $row->RANGE_NAME. '</option>';
}
?>
</select>
</div>
$('.datepicker').datepicker({
autoclose: true,
format: 'dd/mm/yyyy',
language: 'fr'
});
Best regards
CodePudding user response:
The following example shoes the event that listens to the change in date of birth selected by user then it passes the dob to the function which calculates the age on the basis of the age it selects the appropriate date range in the date range select box.
const getAge = (dob) => {
return ~~((new Date()-new Date(dob))/(31556952000));
};
$('#birth-date').change(function() {
const date = $(this).val();
const age = getAge(date);
if(age < 18)
$('#date_range').val(1).change();
else if(age >= 18 && age < 25)
$('#date_range').val(2).change();
else if(age >= 25 && age < 50)
$('#date_range').val(3).change();
else
$('#date_range').val(4).change();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="birth-date" >BIRTH DATE</label>
<input type="date" name="birth-date" id="birth-date" >
<br />
<label for="date_range" >AGE RANGE</label>
<select name="date_range" id="date_range">
<option></option>
<option value="1">- 18</option>
<option value="2">btw 18 25</option>
<option value="3">btw 25 50</option>
<option value="4">50 </option>
</select>
</div>
If you want to get better control over date formating and ease the calculations you can use moment.js e.g. the getAge function can be updated as following
const getAge = (dob) => {
const date = moment(dob, 'DD/MM/YYYY');
return moment().diff(date, 'years');
};