Izuagbala
Izuagbala

Reputation: 449

JavaScript: Get the value of a date input field using Jquery

I want to get the value of a date input field and alert it,but I always get an empty string or undefined. Any help on how to get the value of this field will be appreciated.

code -

var end = $('#datetimepicker2').val();

$('#sub').on('click', function () {
    alert(end);
});

HTML CODE

<input type="text" class="form-control input-group-sm" placeholder="Enter Date" id="datetimepicker" aria-label="...">

I am using bootstrap-datepicker plugin to get the date. EDIT: I want to get the date in yyyy/mm/dd format and store it in a variable

Upvotes: 2

Views: 14096

Answers (3)

Timothy Wood
Timothy Wood

Reputation: 487

When var end = $('#datetimepicker2').val(); gets executed, the <input id="datepicker2"> element has no value.

It remains empty because you have not defined an event handler to update it when the value has changed. The following should be a working example of what you are trying accomplish.

<table>
    <tr>
        <td><strong>Date Time Picker:</strong></td>
        <td>
            <input id="datetimepicker2" class="datetimepicker" value=""/>
        <td>
        <td><button id="sub">Submit</button></td>
    </tr>
</table>

<script>
    // If the datepicker2 input is empty, this will be empty, even after you change it.
    var end = $('#datetimepicker2').val();
    $('#datetimepicker2').datetimepicker();

    // This will update the "end" variable as it changes.
    $(document).on('change', '#datetimepicker2', function() {
        end = $(this).val();
    });

    $(document).on('click', '#sub', function () {
        alert(end);
    });
</script>

ps: I changed the $(x).on(event,function) to $(document).on(event,element,function) because I've had better results with this as the DOM is manipulated over time.

Upvotes: 3

Gabriel Mesquita
Gabriel Mesquita

Reputation: 2391

You must use the same id in your jquery like this:

$('document').ready(function(){
    $('#sub').on('click', function () {
        var end = $('#datetimepicker').val()
        alert(end);
    });
)}

And you probably want to get the value after you select the date and click the #sub button.

Upvotes: 0

j9070749
j9070749

Reputation: 945

 $('#datePicker').datepicker()
        .on("input change", function (e) {
            //$('.loadingBackground').show();

            var date = $(this).datepicker('getDate');
alert(date);

});

This will alert the date every time the date is changed.

Or on the click event:

var date = $('#datePicker').datepicker('getDate');
$('#sub').on('click', function () {
    alert(date);
});

Upvotes: 0

Related Questions