Search code examples
htmlbootstrap-datepicker

Writing a non-date type in an <input /> date


Using Datepicker for Bootstrap v1.9.0

I need to select week by year (in the format WW/YYYY), I have the following code:

html

<div class="form-group col-12">
    <label asp-for="EngineeringChange.FinishedGood.Week">Semana</label>
    <input type="text" id="weeklyDatePicker" class="form-control" placeholder="Select Week" />
    <input asp-for="EngineeringChange.FinishedGood.Week" class="form-control weeklyDatePicker" placeholder="Select Week" type="hidden" />
    <span asp-validation-for="EngineeringChange.FinishedGood.Week" class="text-danger"></span>
</div>

jquery

$(document).ready(function () {
    moment.locale('en', {
        week: { dow: 0, doy: 0 }
        // Sunday is the first day of the week
    });

    //Initialize the datePicker(I have taken format as mm-dd-yyyy, you can     //have your own)
    $("#weeklyDatePicker").datepicker({
        format: 'MM-DD-YYYY'
    });

    //Get the value of Start and End of Week
    $('#weeklyDatePicker').on('changeDate', function (e) {

        var week = moment(e.date, "MM-DD-YYYY").week();
        var year = moment(e.date, "MM-DD-YYYY").year();
        var end = week + '/' + year;
        $("#weeklyDatePicker").val(end);
        console.log(end + "AFTER: " + $("#weeklyDatePicker").val());
    });
});

I can get it working as such: enter image description here But as soon as I close the picker, it automatically changes to this: enter image description here

I believe this is because #weeklyDatePicker is of the type date, but what is the workaround?


Solution

  • Adding the option forceParse:false will stop the conversion.

    $("#weeklyDatePicker").datepicker({
        ...
        forceParse: false,
    });
    

    PS: On a sidenote, what I find strange is that if I change the code to (and before the forceParse:false changes):

    $('#weeklyDatePicker').on('changeDate', function (e) {
    
        console.log("BEFORE" + $(".weeklyDatePicker").val());
    
        var week = moment(e.date, "MM-DD-YYYY").week();
        var year = moment(e.date, "MM-DD-YYYY").year();
        var end = week + '/' + year;
        $("#weeklyDatePicker").val("" + end);
    
        console.log(end + "AFTER: " + $("#weeklyDatePicker").val());
    
    });
    

    The BEFORE and AFTER print will be correct, but the display will not. Meaning if I select a week and close the datapicker, it unintentionally changes to dd/mm/yyyy format, but when I open it again the BEFORE print will show the correct value (ww/yyyy), meaning the value of the input is indeed what I want, but for some reason it changed it's display.