single calendar bootstrap-datepicker allowing users to select date ranges

Is it possible to create a single calendar range date picker with Bootstrap instead of using two separate calendars? Currently, I have implemented a solution with two calendars.

$('#datepicker').datepicker({
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>

<div class="input-daterange input-group" id="datepicker">
    <input type="text" class="input-sm form-control" name="start" />
    <span class="input-group-addon">to</span>
    <input type="text" class="input-sm form-control" name="end" />
</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>

I am seeking guidance on how I can modify this setup to utilize just one calendar for the date picker functionality. Any insights or solutions are greatly appreciated as I haven't found a definitive answer elsewhere.

Answer №1

For those seeking a solution, here is an answer that may be of help.

 $('#date').datepicker({
    startView: 0,
    minViewMode: 0,
    maxViewMode: 2,
    multidate: true,
    multidateSeparator: "-",
    autoClose: true,
    beforeShowDay: highlightRange,
  }).on("changeDate", function(event) {
    var dates = event.dates,
        elem = $('#date');
    if (elem.data("selecteddates") == dates.join(",")) return;
    if (dates.length > 2) dates = dates.splice(dates.length - 1);
    dates.sort(function(a, b) { return new Date(a).getTime() - new Date(b).getTime() });
    elem.data("selecteddates", dates.join(",")).datepicker('setDates', dates);
  });

  function highlightRange(date) {
    var selectedDates = $('#date').datepicker('getDates');
    if (selectedDates.length === 2 && date >= selectedDates[0] && date <= selectedDates[1]) {
      return 'highlighted';
    }
    return '';
  }
  .highlighted {
    background-color: #99ccff;
  }
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<input type="text" id="date">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script>

Answer №2

Utilizing Bootstrap and Datepicker libraries for implementation

<!DOCTYPE html>
<html>
<head>
  <title>Date Range Picker</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css">
</head>
<body>

<div class="container">
  <h1>Date Range Picker</h1>
  <div class="input-group">
    <input type="text" class="form-control" id="date-range" placeholder="Select Date Range">
    <div class="input-group-append">
      <span class="input-group-text">
        <i class="fa fa-calendar"></i>
      </span>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="630e0c0e060d1723514d515a4d52">[email protected]</a>/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>

<script>
$(document).ready(function() {
  $('#date-range').daterangepicker({
    opens: 'left',
    drops: 'down',
    autoApply: true,
    locale: {
      format: 'YYYY-MM-DD',
      separator: ' - ',
      applyLabel: 'Apply',
      cancelLabel: 'Cancel',
      fromLabel: 'From',
      toLabel: 'To',
      customRangeLabel: 'Custom',
      daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
      monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
      firstDay: 0
    }
  });
});
</script>

</body>
</html>

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

Determine if the specific subroute has a child using vue-router

After checking similar questions on stackoverflow without success, I am seeking a solution. I am attempting to determine if a subroute is a child of a specific route in order to display a container. Unfortunately, the following code snippet does not work: ...

Issue with onClick event not firing when using option tag in React

onClick event seems to have an issue with the <option> tag. How can we successfully use the onClick event with the select option tags while assigning different parameters to each option? async function setLanguage(language) { ...

What is the best way to paste plain text into a Textarea without any formatting?

A challenge I am facing in my project is related to copying and pasting text into a Textarea. When a user copies text, the style of the text is also inserted along with it. However, when the user manually types the text, it gets inserted correctly without ...

Combine similar JSON objects into arrays

I'm working with a dataset returned by a library, and it's structured like this: var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}] My goal is to group the "fName" values together and add '[]' to achieve the fo ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...

Tips for resolving the issue of CSS blocks disappearing when designing a webpage

When creating a responsive web page, the child block "overflows" from the parent block. This causes the entire page to shift to the left and an empty bar appears on the right side, moving all the content. I need to ensure that all content is positioned cor ...

Sending JSON data from a Django view to a JavaScript function

I am trying to pass JSON data to JavaScript. I need the JSON structure to be like this: data: [ { value: 335, name: 'Coding' }, { value: 310, name: 'Database ...

Name of Document (changing from php to ?)

Greetings! Currently, I am utilizing PHP to include the document name as an example. folder/<?phpecho basename(__FILE__, '.' . pathinfo(__FILE__, PATHINFO_EXTENSION));?>_button.png I have observed that using PHP for this purpose and havin ...

Retrieve data from an AJAX call and PHP script upon successful completion

Utilizing AJAX (jQuery), my aim is to submit a form to user-ajax.php and expect the page to echo back a response like "success". In my AJAX code, I am checking the response value for success but it's not working as expected. Below is the PHP code snip ...

Can I access properties from the index.html file within the Vue.js mount element?

<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="widt ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...

Tips on showing an api call response in Reactjs

I am a beginner in Reactjs and currently working with nextjs. I have been trying to integrate a "newsletter" feature into my project. I have created a component for this which is functioning properly. However, I am facing an issue with displaying the "succ ...

Explore our interactive map and widget features that will seamlessly fill your browser window for a

Struggling to make a webpage with a Google Map, Chart, and Grid expand to fill the available space on the screen. Tried various CSS tricks but nothing seems to work. Check out this simplified example in JsFiddle that showcases the issue: http://jsfiddle. ...

Having an issue with the Show/Hide Javascript toggle on the same page. Multiple hidden texts are appearing simultaneously. Seeking a solution without the use of JQuery

This code is functioning efficiently. I am looking for a way to display and conceal various texts using different expand/hide links within multiple tables on the same page. I prefer to achieve this without using JQuery, just like in this straightforward sc ...

React-xarrows is a stunning display of multiple arrows overlapping each other in a mesmerizing fashion

I am currently using the react-xarrows library within my project to connect tables in a diagram. However, I have encountered an issue where multiple links between two tables cause the arrows to overlap, resulting in only one visible link instead of the int ...

Is it possible to use the AngularJS function with the <div> HTML element?

I am facing an issue with displaying a modal when clicking on a <div> element. The function assigned to show the modal by changing the CSS property 'display' from 'none' to 'block' works fine when attached to a button, b ...

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

How can you efficiently update another ng-model value based on a select input in AngularJS using ng-change?

<select data-ng-init="selectedItem='previewWidth = 1920; previewHeight = 1080'" data-ng-model="selectedItem" data-ng-change="GetNewData(); {{selectedItem}}"> <option value="previewWidth = 1920; previe ...