是否可以使用带有`onchange`事件的jQuery日期选择器?

时间:2016-01-17 17:03:55

标签: javascript jquery datepicker symfony

我有一个查询数据库的页面,并返回两个日期之间的所有发票。如果没有提供默认值,控制器会提供默认值,但是我无法弄清楚如何获取onchange事件来生成要加载的新路由。

控制器:

$min$max

之间正确返回记录的查询
/** *********************************************************************************************
* @Route("/invoices/view/monthly/{min}/{max}"  ,name="view_monthly_invoices", defaults={"min"="2016-01-01", "max"="now"})
********************************************************************************************** */
public function viewMonthlyInvoicesAction(Request $request, \DateTime $min, \DateTime $max)
{
$em = $this->getDoctrine()->getManager();
$invoicesinrange = $em->getRepository('AppBundle:Invoice')->invoicesWithinDates($min, $max);

return $this->render('invoices/view.daterange.invoices.html.twig', array(
    'invoicesinrange' => $invoicesinrange,
    'min'=>$min->format('Y-m-d'),
    'max'=>$max->format('Y-m-d'),
));
}

HTML:

这是我正在尝试使用的DOM中的html

<div class="row">
    <label for="invoice_invoicedate" class="required">Minimum Date</label>
    <input type="text" id="min_date" name="invoice[mindate]" required="required" class="datepicker" value="16-Jan-2016" />

    <label for="invoice_invoicedate" class="required">Maximum Date</label>
    <input type="text" id="max_date" name="invoice[maxdate]" required="required" class="datepicker" value="17-Jan-2016" />
</div>
有问题的

脚本:

这就是我一直把自己打结的结果。有没有办法确定哪个字段是change d然后更新路由才能正确加载?

$('#min_date, #max_date').on('change', function () {
    var date = $(this).val(); 
    if (date) { 
        window.location = '/invoices/view/monthly/' . date . '/' . otherdate; 
    }
    return false;
});

...如果它具有相关性,我也有这个jQuery UI脚本,用于多个页面:

$(function() {
    $( ".datepicker" ).datepicker({
        dateFormat: "dd-M-yy",
        changeYear: true,
    })
});

1 个答案:

答案 0 :(得分:0)

可以使用is()找出哪一个被操作并相应地分配url变量

// store elemnts in collection to make it easy to get the other one when changed
var $datePickers = $(".datepicker").datepicker({
    dateFormat : "dd-M-yy",
    changeYear : true,
}).on('change', function () {
    var $el = $(this),
            // simple filter to get other input
            $otherInput = $datePickers.not(this),
            // boolean based on which was changed
            isMinDate = $el.is('#min_date'),
            // ternaries to assign vaariables
            date = isMinDate ? $el.val() : $otherInput.val(),
            otherdate = isMinDate ? $otherInput.val() : $el.val();
    // make sure both dates exist - should be validated more
    if (date && otherdate) {
        window.location = '/invoices/view/monthly/' + date + '/' + otherdate;
    }
    return false;
});