0

Hi I am running an a jQuery function to send some data to an ajax request I have an if statement to get the active elements within a dropdown to pass the selection to the ajax request. Like so:

 $('#filters #region_dd ul.dropdown li a').click(function (e) {
    $('#filters #region_dd ul.dropdown li a').removeClass('active');
    $('#centre_dd > .active').text("Select a Centre").toggleClass('active');
    $('#centre_dd > ul.dropdown li a.active').toggleClass('active');

    console.info('Selected Region: "' + $(this).attr('href') + '"');

    if ($('.date-selection li a.active')) {
      date =  $('.date-selection > li a.active').attr('href');
    } else if($('#year_dd .dropdown.year-selection > li > a.active')) {
      date =  $('#year_dd .dropdown.year-selection > li > a.active').attr('href');
    } else {
      date = null;
    }
    var region = $(this).attr('href');
    filterData.update('/overview', region, null, date);
  });

However the else if condition is never caught even when that .year-selection > li > a.active is true if the .date-selection > li > a.active is active then this passed through. Any ideas what I've doing wrong with my else if??

3
  • may be because you are calling .removeClass('active'); before the if condition Commented Mar 22, 2015 at 10:37
  • not on the .date-selection or .year-selection though @ArunPJohny Commented Mar 22, 2015 at 10:38
  • @ArunPJohny the first if doesn't fail but the else if does Commented Mar 22, 2015 at 10:41

1 Answer 1

3

One problem I can see is you are passing a jQuery object to the if condition, which is always truthy, so irrespective of whether there is an element matching the criteria .date-selection li a.active, the if block will get executed.

if ($('.date-selection li a').hasClass('active')) {
    date = $('.date-selection > li a').attr('href');
} else if ($('#year_dd .dropdown.year-selection > li > a').hasClass('active')) {
    date = $('#year_dd .dropdown.year-selection > li > a.active').attr('href');
} else {
    date = null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.