The validation for the start and end dates in the datepicker is not functioning properly when

I have integrated a bootstrap date picker into my website. However, I am encountering an issue where the end date validation does not update when I change the start date after the initial selection.

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<script !src="">
  // Include Date Range Picker -->
  let format = 'yyyy-mm-dd';
  // Start date
  $('.start-date').datepicker({
    startDate: new Date(),
    format: format,
    autoclose: true
  });
  // End date
  $('.start-date').on("change", function() {
    $('.end-date').val('');
    $('.end-date').datepicker({
      startDate: $('.start-date').val(),
      format: format,
      autoclose: true
    });
  })

</script>

Even though I am fetching the updated value of $('.start-date').val() in the onchange function, the limitation on the end date remains unchanged.

Answer №1

It is not recommended to include the code $('.end-date').datepicker within the $('.start-date').on('change' listener because this will result in attaching the datepicker every time the .start-date changes.

To prevent this issue, place the .end-date datepicker outside of the 'onchange' function and simply include $('.end-date').val(''); to clear the field when needed.

Please let us know if everything functions correctly after making these adjustments.

Answer №2

Give this solution a try.

const dateFormat = 'mm/dd/yyyy';
// Setting up start date
$('.start-date').datepicker({
    startDate: new Date(),
    format: dateFormat,
    autoclose: true
});

// Setting up end date
$('.end-date').datepicker({
    startDate: new Date(),
    format: dateFormat,
    autoclose: true
});

// Event listener for start date change
$('.start-date').datepicker().on("changeDate", function() {
    let newStartDate = $('.start-date').datepicker('getDate');

    // Reset end date and update start date in dropdown
    $('.end-date').datepicker('update', '');
    $('.end-date').datepicker('setStartDate', newStartDate);
})

Answer №3

$(document).ready(function() {
  $("#startDate").datepicker({
    format: 'yyyy-mm-dd',
    startDate: new Date(),
    autoclose: true,
    autoclose: true,
  }).on('changeDate', function(selected) {
    var minDate = new Date(selected.date.valueOf());
    $('#endDate').datepicker('setStartDate', minDate);
  });

  $("#endDate").datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
  }).on('changeDate', function(selected) {
    var minDate = new Date(selected.date.valueOf());
    $('#startDate').datepicker('setEndDate', minDate);
  });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet" />
<form autocomplete="off">
  <input type="text" id="startDate">
  <input type="text" id="endDate">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>

Note: Utilize the changeDate event to enhance functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js application failing to display images fetched from the server

When I'm running my Vue.js app locally, the images are loading fine from the "src/assets" folder. However, when I deploy the app to Firebase, the images are not displaying and I get a 404 error. What could be causing this issue? I have tried using: ...

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

Leveraging HTML tables for input purposes

Just starting out with php, HTML, and mysql. Using HTML tables for the first time here. Created an HTML table filled with data from a MySQL table. Planning to use this table as a menu where users can click on a cell with a specific date. The clicked date ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

Tips for showcasing a designated set of numbers in Vue Js while iterating?

Is there a way to specifically target numbers during a loop? For example, I only want to retrieve numbers 5 and above or within a certain range that I specify. <select name="" id="input" class="form-control" v-model="selectcompetitionyear"> < ...

Implementing a 'Load More' button for a list in Vue.js

I am currently working on adding a load more button to my code. While I could achieve this using JavaScript, I am facing difficulties implementing it in Vue.js. Here is the Vue code I have been working with. I attempted to target the element with the compa ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Passing an array of objects as properties in React components

My functional component looks like this: function ItemList({ items }: ItemProps[]) { return <p>items[0].name</p> } Here is how I'm creating it: <ItemList items={items} /> The array items contains objects in the format [{name: &ap ...

Not every time you call the AngularJS run method does it actually execute

Working on a simple Angular app, I wanted to implement a user login check and redirection. However, I encountered an issue where accessing the home page from the form site resulted in inconsistent behavior - sometimes redirecting and other times showing ...

It is not possible for $_GET to loop through an array

I have a list of values called dataId obtained from checkbox selections, and I want to send it via a GET AJAX request: dataId = 1, 2, 16, 15, 17, 3, 14, 5, 9, 11; URI = "<?php echo site_url('Terpasang/Update_Kebutuhan_ke_Terpasang')?>"; $. ...

Master the art of sending multiple asynchronous requests simultaneously with suspense in Vue 3

Utilizing <Suspense>, I am handling multiple requests in my child component using the await keyword: await store.dispatch("product/getProduct", route.params.id).then(res => productData.value = res); await store.dispatch("product/get ...

In search of assistance with a persistent react.js error plaguing my work

I keep encountering an error whenever I run npm start on a new project. Does anyone have any insight on how to resolve this issue? The problem might lie within the project dependency tree rather than being a bug in Create React App. Here is what you can ...

Stopping Popups in Chrome When Printing with JavaScript

Javascript function printPage(htmlPageContent) { var newWindow = window.open("about:blank"); newWindow.document.write(htmlPageContent); newWindow.print(); } In this code snippet, we are creating a new window 'newWindow' and then using ...

TypeScript combined with Vue 3: Uncaught ReferenceError - variable has not been declared

At the start of my <script>, I define a variable with type any. Later on, within the same script, I reference this variable in one of my methods. Strangely, although my IDE does not raise any complaints, a runtime error occurs in my console: Referenc ...

Display JSON data using Vue.js

Trying to display JSON file results using Vue.js, with the goal of showing the result in a value. Here is the code snippet: data () { return { fetchData: function () { var self = this; self.$http.get("/api/casetotalactivation", functio ...

What is the best way to convert a circular JSON object to a string

Is there a way to stringify a complex JSON object without encountering the "Converting circular structure to JSON" error? I also need its parser. I am facing issues every time I try to use JSON.stringify and encounter the "Converting circular structure to ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Form submission using Jquery not functioning properly in Firefox

Having an issue with the .post() function not working on Firefox, but functioning fine on Chrome. This is the code I am using: function saveD() { frm = $('#saveDetailsForm'); $.post(frm.attr('action'), frm.serialize(), fun ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

Implementing ES6 Angular directives with two-way isolated binding

I'm really struggling to understand how isolating scopes function in my code. Interestingly, everything seems to work fine when I remove the scope part of the directive. Can someone please shed some light on what I might be overlooking? export func ...