I’m working on a web application where users are required to select a minimum of two time slots for booking appointments. Additionally, these selected time slots must be consecutive, meaning that there should be no gaps between them. Despite implementing JavaScript validation to enforce this requirement, the system still identifies selected time slots as non-consecutive, even when they are. Any insights on why this validation isn’t working as expected would be greatly appreciated.
enter image description here
enter image description here
This is my html code with the JavaScript function:
<!DOCTYPE html>
<html>
<head>
<title>Time Slot Selection</title>
<style>
.available {
color: rgb(37, 37, 37);
}
.not-available {
color: red;
}
</style>
<script>
function validateSlots() {
// Get the selected checkboxes
var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
var selectedSlots = Array.from(checkboxes).map(checkbox => parseInt(checkbox.value));
console.log("Selected Slots:", selectedSlots); // Log selected slots
// Check if at least 2 slots are selected
if (selectedSlots.length < 2) {
alert("Please select at least 2 slots.");
return false;
}
// Sort the selected slots in descending order
selectedSlots.sort((a, b) => b - a);
// Check if the selected slots are consecutive
for (var i = 0; i < selectedSlots.length - 1; i++) {
// Calculate the difference between consecutive slots
var difference = selectedSlots[i] - selectedSlots[i + 1];
// Log the index of the selected slot
console.log("Index:", i);
// Log the difference between consecutive slots
console.log("Difference:", difference);
// If the difference is not 1, slots are not consecutive
if (difference !== 1) {
alert("Selected slots must be consecutive.");
return false;
}
}
// If all checks pass, allow form submission
return true;
}
</script>
</head>
<body>
<h1>Select a Time Slot for {{ selected_date }}</h1>
{% if error_message %}
<p>{{ error_message }}</p>
{% endif %}
<form method="post" action="{% url 'sbapp:confirm_slots' %}" onsubmit="return validateSlots()">
{% csrf_token %}
<ul>
{% for slot in time_slots reversed %}
<li>
<!-- Wrap the entire time slot display in a span -->
<span {% if slot.slot.status == 'not_available' %} class="not-available" {% endif %}>
<!-- Display the time slot -->
{{ slot.slot.start_time }} - {{ slot.slot.end_time }}
<!-- Display the checkbox if slot is available -->
{% if slot.slot.status == 'available' %}
<input type="checkbox" name="selected_slots" value="{{ slot.serial_number }}">
{% endif %}
</span>
</li>
{% endfor %}
</ul>
<input type="hidden" name="selected_date" value="{{ selected_date }}">
<input type="submit" value="Confirm Selection">
</form>
</body>
</html>
Whenever I select 2 consecutive slots; I want them to get booked. That’s it here.
Mihir Yadav is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.