Datepicker insert date and week in field

2019-08-04 17:19发布

问题:

I hope that one of you experts can help me with a problem in datepicker.

I have a page with the following fields

date, week, item number, description, price

I can get the date picker to work for date and week but only if I assign datepicker to each of them.

My problem is that I want it so that when you select the date in the date field then puts datepicker automatically week number into the week field so you do not need datepicker 2 times but only once.

Unfortunately I do not have much knowledge of javascript and therefore hope there is someone who can help me

Many thanks in advance

Niels Baeklund

回答1:

With the help of this answer, I learnt to get the week number using the following method.

Date.prototype.getWeek = function() {
        var onejan = new Date(this.getFullYear(),0,1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
    } 

Then I have used this to get the weeknumber in the datepicker like

$('#datepicker').datepicker({
    onSelect: function (date) {
        var dat = new Date(date); //convert string to date
        var weekNo = dat.getWeek();
        $('#week').val(weekNo);

    }
});

JSFiddle1

Updates:

After a few research, I ended up with a nice solution within jQuery UI datepicker.

$('#datepicker').datepicker({
    onSelect: function (dateText, inst) {
        $('#week').val($.datepicker.iso8601Week(new Date(dateText)));
    }
});

JSFiddle2

Hope you understood.