Ruth Young
Ruth Young

Reputation: 888

jQuery event handler with multiple links won't work

I'm trying to append the jQuery ui-datepicker and I can't get the event handler working:

$( '.ui-datepicker' ).on('click', 'a.ui-datepicker-next', 'a.ui-datepicker-prev', function( event ) {
    event.preventDefault();
        console.log("CLICK");
});

I've got nothing logging to the console when I click the links. Here is the html:

<div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"...>
    <div class="ui-datepicker-header ui-widget-header ui-helper-clearfix- ui-corner-all">
        <a class="ui-datepicker-next ui-corner-all"...></a>
        <a class="ui-datepicker-prev ui-corner-all"...></a>
        ...

What do I need to put as the event handler to trigger this? The jQuery is in a <script>jQuery here</script> in the footer of my html.

EDIT: links were incorrect - a.ui-datepicker-month and a.ui-datepicker-year changed to a.ui-datepicker-next and a.ui-datepicker-prev

Thanks

Upvotes: 1

Views: 36

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Your syntax isn't quite right. The selectors need to be comma delimited but in the same string. Try this:

$('.ui-datepicker').on('click', 'a.ui-datepicker-month, a.ui-datepicker-year', function(e) {
  e.preventDefault();
  console.log("CLICK");
});

Note: 'a.ui-datepicker-month, a.ui-datepicker-year'. Also note the use of e, not event, as that will override the global event object that some browsers have.

*Update after question was edited:

There's two other issues. Firstly the correct classes are a.ui-datepicker-prev and a.ui-datepicker-next. Also, the ui.-datepicker element doesn't exist on load of the DOM, hence there's nothing to bind the event to. To fix this you can use $(document), although ideally you should use the nearest parent element to those you want to target thats in the DOM on load. Try this:

$(document).on('click', 'a.ui-datepicker-prev, a.ui-datepicker-next', function(e) {
  e.preventDefault();
  console.log("CLICK");
});

Working example

Upvotes: 2

Related Questions