Guide on extracting the date selected from a Bootstrap datepicker and displaying it in a separate div

I'm currently attempting to extract the date from a button and display it in another div. Initially, I tried using the input tag method but faced some issues. Therefore, I switched to employing the button option with an icon. My main challenge now is figuring out how to retrieve the date and present it elsewhere.

<button type="button" class="btn btn-icon btn-primary w-full" id="date" data-plugin="datepicker">
<i class="icon wb-calendar" aria-hidden="true">
</i></button>
<div id="show-date"></div>

Below is the JavaScript code:

$(function() {

  var showdate = document.getElementById( 'show-date' );
    $("#date").datepicker();
    $("#date").on("change",function(){
        var selected = $(this).val();
        showdate.selected.show;
     
    });
});

Answer №1

There are several issues with your code. Firstly, a button cannot trigger the change event; it has to be changeDate.

Secondly, to retrieve the date, you need to use ev.date because the button's value will not update during the changeDate event.

$(function() {

  var showdate = $("#show-date")
  $("#date").datepicker().on('changeDate', function(ev) {
    var selected = ev.date
    showdate.text(selected)
  });
});

Demo

$(function() {

  var showdate = $("#show-date")
  $("#date").datepicker().on('changeDate', function(ev) {
    var date = new Date(ev.date);
    var selected = ((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear()
    showdate.text(selected)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" integrity="sha512-mSYUmp1HYZDFaVKK//63EcZq4iFWFjxSL+Z3T/aCt4IO9Cejm03q3NKKYN6pFQzY0SBOr8h+eCIAZHPXcpZaNw==" crossorigin="anonymous"
  referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js" integrity="sha512-T/tUfKSV1bihCnd+MxKD0Hm1uBBroVYBOYSk1knyvQ9VyZJpc/ALb4P0r6ubwVPSGB2GvjeoMAJJImBG12TiaQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<button type="button" class="btn btn-icon btn-primary w-full" id="date" data-plugin="datepicker">
<i class="icon wb-calendar" aria-hidden="true">
</i></button>
<div id="show-date"></div>

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

Guide to utilizing dat.gui for managing the speed of rotation of a model within three.js?

Trying to control the rotation speed of my model, I decided to use dat.gui for this task. In my render script, the following code snippet was added: function render() { group.rotation.y -= controls.rotation; rendere ...

Exploring the Power of Math Set Functions with Associative Arrays in Javascript

Is there a way to find the variance between two sets of objects in Javascript? For example: var obj1[0] = { name : 'test1' , type : 'test2' }; var obj1[1] = { name : 'test2' , type : 'test3' }; var obj2[0] = { name ...

The way images appear can vary between desktop and mobile devices

I am in the process of creating a photography website with a simple goal of displaying images down the page one after another. However, I am encountering issues with uniform display across various desktop and mobile platforms. The site appears perfect on i ...

What is the best way to ensure that these social icons are perfectly centered on the page across all web browsers?

Visit my website here: foxweb.marist.edu/users/kf79g/contact.php I'm stuck on the final step needed to deploy my website and finish it. The issue I'm facing is with the social icons when viewed on medium and small screens. I want them to be cent ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

Add the child's input query first and then concentrate on it

I have successfully appended a div with a child input, but I am facing an issue where the newly appended input is not getting focused when added. $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper ...

How to prevent labels from overlapping textboxes when the labels are lengthy using CSS

I am having an issue with an asp control that renders as a text area. I have applied some CSS to style it, but I am facing a problem where a long label is overlapping the textbox. Is there any CSS I can add to push the textbox down if the label gets too lo ...

Can someone please provide instructions on how to customize the textfield caret using JavaScript?

Is there a way to modify the appearance of a caret so that it resembles a letter or some other shape? Appreciate any suggestions. Thank you! ...

Changing the time zone of a UTC date string while preserving the original format

Is there a way to convert a UTC date string to the current user's timezone while keeping the original date string format intact? Take for example the following code snippet that accomplishes this: var data = '2017-04-24 12:06:37'; var date ...

Customize tab background color in Material-UI by utilizing a styledTab component with a passed prop

I've customized this tab to have my desired style: import { withStyles } from "@material-ui/core/styles"; const StyledTab = withStyles((theme) => ({ root: { backgroundColor: "yellow", }, }))((props) => { const { shouldSetBackgroundCol ...

Build an immersive experience by incorporating threejs into A-Frame to develop a spherical environment filled with 360-degree videos

I've been working on a VR project that involves 360° videos in VR. My concept was to construct a sphere and apply a 360° video as the material. I've already managed to create my own Sphere Component and map a 360° image onto it! Similar to t ...

Unable to utilize the .keyCode method within a query selector

Trying to utilize .keyCode in JavaScript to identify a pressed key, but the console consistently displays null after each key press. Below is the relevant CSS code: <audio data-key="65" src="sounds\crash.mp3"></audio> ...

Is it acceptable to conceal items by utilizing display:none?

When dealing with a dynamic website that includes components from various plugins, is it acceptable to hide elements temporarily or permanently using display:none? Sometimes clients may request certain items to be hidden from the page, so instead of removi ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

Removing data with the click of a button

I have successfully implemented a feature where clicking the "add to my stay" button displays the name and price data. Subsequently, it automatically changes to a remove button when clicked again for another addon. If I press the remove button of the first ...

Personalize the appearance of a component using React Bootstrap styling

I am looking to customize the default style of a react-bootstrap component. For instance, when using the Panel component, I would like to make the title bold. How can I accomplish this without losing the default styles of a "warning" panel when using bsCl ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Unable to retrieve information from the json-server

For my current project in Backbone.js, I'm utilizing the json-server package to populate it with data. I've created a db.json file containing the data and executed the command json-server --watch db.json. The server started successfully and is ru ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...