Search code examples
javascriptjsfprimefaces

DatePicker: Select single date when using range selection


I have a range DatePicker from Primefaces. But I also want to be able to just select one date.

But if i do so, i won't get any values, just a empty array. This is because the internal function (which i can't modify) only returns something when two values are given. Or at least I think that.

The workaround which i thought of was just taking the first value of the array by calling it with a javascript function, but i can't access it, because the PF function has neither a function name nor a class.

Here the code of the PrimeFaces function:

 if (this.isRangeSelection()) {
                                if (this.value && this.value.length) {
                                    var b = this.value[0],
                                        g = this.value[1];
                                    d = this.formatDateTime(b);
                                    if (g) {
                                        d += " " + this.options.rangeSeparator + " " + this.formatDateTime(g)
                                    }
                                }
                            }

Here is my poor javascript attempt:

<script type="text/javascript">
    function getArrayValue(){
        console.log("inFunction");
        console.log(window.d.value[0]);
    }
    </script>

This is called with this:

<div class="p-field p-col-12 p-md-4">
    <p:datePicker id="range" selectionMode="range"
            value="#{SearchBean.range}" onblur="getArrayValue()">
    </p:datePicker>
 </div>

Thanks for your help in advance! :)


Solution

  • I just helped a friend do the same thing that sets the range to both dates being the same you can do it with this JS...

    <script type="text/javascript">
    function adjustDateRange(widgetVar) {
        var widget = PF(widgetVar);
        var dates = widget.getDate();
        if (dates[0] && !dates[1]) {
            dates[1] = dates[0];
            widget.jq.data().primeDatePicker.updateModel(null, dates);
        }
    }
    </script>
    

    Then in your DatePicker...

    <p:datePicker id="range" 
    widgetVar="wgtRange" 
    selectionMode="range" 
    value="#{SearchBean.range}" 
    onblur="adjustDateRange('wgtRange')">
    </p:datePicker>