I have Leave request form
where the employees are able to request different type of leaves such as paid leave, non paied leave, leave for blood donation etc.
Those types are stored in Mysql
table and i am visualising them in dropdown
via this code:
<div class="form-group">
<label for="leavetype">Leave type*:</label>
<select name="leavetype" id="leavetype" required>
<option disabled selected value="">-- Select--</option> <?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT leavetype FROM leavestypes");
while($data = mysqli_fetch_array($records))
{
echo "
<option value='".$data['leavetype'] ."'>" .$data['leavetype'] ."</option>";
}
?>
</select>
What i want is to limit allowed days, for example if the user select Leave for blood donation
to be able to use only two days in the date pickers. Here is how the user pick dates:
<div class="form-group">
<label for="startdate">Start:*</label>
<input required="" class="form-control" name="startdate" id="startdate" type="date">
</div>
<div class="form-group">
<label for="tilldate">End:*</label>
<input required="" class="form-control" name="tilldate" id="tilldate" type="date">
</div>
I am trying to limit it via script in the end of the file:
<script>
const form = document.querySelector('#leave-form');
form.addEventListener('submit', function(event) {
const startDate = new Date(document.querySelector('#startdate').value);
const endDate = new Date(document.querySelector('#tilldate').value);
const leavetype = document.querySelector('#leavetype').value.trim();
if (endDate < startDate) {
alert('end date cannot be before start date');
event.preventDefault();
} else if (
leavetype === 'leave for blood donation - two days allowed' ||
leavetype === 'test2 - two days allowed' ||
(leavetype === 'leave for marrage - two days allowed ' && ((endDate - startDate) / (1000 * 60 * 60 * 24) + 1 > 2)) {
alert('You can use only two days for this type of leave');
event.preventDefault();
}
});
</script>
I was trying using includes()
method instead of ===
but not working again.
The problem is that when I have this script if I select some of those type of leaves its always in alert no matter how many days I select in the date picker.
2
Answers
Problem fixed. If someone looking here this is the solution I used:
You need to group the "OR" with a parenthesis in your else-if statement
Because in your example, it triggers when :
leavetype === 'leave for blood donation - two days allowed'
leavetype === 'test2 - two days allowed'
(leavetype ==='leave for marrage - two days allowed ' && ((endDate - startDate) / (1000 * 60 * 60 * 24) + 1 > 2)
I’m guessing what you wanted to do is this: