Jquery Add Datepicker to Input Fields

Jquery Add Datepicker to Input Fields

I am using the jquery datepicker on a number of text input fields in my forms. I typically bind it to the input(s) as follows:

$(function() {
  $("#date_due").datepicker();
});

In certain circumstances, the id of the field that I am referencing may not be an input field, but I still want to use the same ID and I dont want the datepicker to be available.

I have tried the following, but it doesnt seem to work (i.e. the datepicker does not appear at all):

$(function() {
  $("#date_due :input").datepicker();
});

Or, put another way, I only want the datepicker to be used if the field is a form text input.

2

2 Answers

I was rather on the cellphone when I commented, so didn't feel like typing a whole bunch of stuff to give you the simple edit, but here it is with some additional info:

$(function() {
  $("input#date_due").datepicker();
});

The selector you want is all elements with the tag name "input" and the id attribute set to "date_due".

The way you had it with "#date_due :input" was selecting child nodes of all elements with the attribute id set to "date_due" and constraining the selection to child nodes with the pseudo-class "input" (witch to the best of my knowledge does not exist), that's why it failed to select your input element.

:input is not a selector, because it's an object, so use the following code:

$("#date_due input").datepicker();

It will apply datepicker to children inputs of #date_date parent div

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.