JonoB
JonoB

Reputation: 5887

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.

Upvotes: 0

Views: 13092

Answers (2)

Kris
Kris

Reputation: 41827

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.

Upvotes: 2

Anatoly
Anatoly

Reputation: 15530

: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

Upvotes: 0

Related Questions