don
don

Reputation: 4522

jQuery Date picker and class assign

I'm using the default jquery's date picker that is triggered by assigning the dp class to an input element. It works fine if i set the class of the element in the html, but if I assign the dp class with js (document.getElementById(eleId).className = 'dp';) the date picker is not triggered when the user clicks on the input. Any idea?

Upvotes: 0

Views: 1508

Answers (2)

Ian
Ian

Reputation: 50905

That's because when you bind the datepicker event to your elements (via the selector, probably $(".dp"), it is only bound to the ones that are found at that point in time. Any time after that, like you said, elements may gain the class (or even lose it). My suggestion would be to do something like this:

<div id="container">
    <!-- Your elements that may or may not have the class "dp" -->
</div>

<script type="text/javascript">
    $("#container").on("click", "dp", function () {
        $(this).datepicker('destroy').datepicker({showOn: 'both'}).focus();
    });
</script>

Where of course you can just put the binding into document.ready, and you can change the options passed to datepicker. Instead of "#container", you could just use "body" or something if you can't narrow it down that much. Also, you'll need to account for onfocus too in some way.

Something I would suggest though, is to use jQuery everywhere you can, since you already include it. For example, your code: document.getElementById(eleId).className = 'dp'; is fine, but why not use the method addClass, and why not use the "#" selector? Like:

$("#" + eleId).addClass("dp");
// and alternatively
$("#" + eleId).removeClass("dp");

A problem with using className is that it isn't as easy to manipulate the class of the element. Using .className = "whatever" overwrites any previous className value - of course, you can account for that, but it's easier to just use jQuery for this. Also, when using removeClass, jQuery may or may not automatically remove any event bindings for the element, where className does nothing like that. If you were to do things like removing and adding classes, it could get messy.

Upvotes: 2

Mihalis Bagos
Mihalis Bagos

Reputation: 2510

It matters when the class is assigned. You have to assign the class before you load up the datepicker module.

Otherwise, the datepicker loads up any inputs it find, then stops. If you assign the class AFTER that event, there won't be any response since the loader has done its job and is not interested in any new items.

Alternatively, you can call the datepicker again, after you assign the class to the element.

Upvotes: 0

Related Questions