1

Why does this not work?

$( ["blog","user","forum"] ).each(function(num,opt) {
    if ( window.location.pathname.indexOf(opt) != -1 ) {
        $('#rb-' + opt).attr('checked','checked');
        return false;
      }
});

When I input $('#rb-blog').attr('checked','checked'); it works as expected?

console.log(typeof opt) produces string and the expected value.

--- UPDATE ---

I've just seen the html is being written to the page via ajax and is executed on .ready() :( Thanks for the help all, much appreciated.

Jongosi
  • 2,305
  • 1
  • 28
  • 31

3 Answers3

1

What the problem could be if the page is not fully loaded and #rb-blog is not available yet.

$(document).ready(function(){
    $( ["blog","user","forum"] ).each(function(num,opt) {
        if ( window.location.pathname.indexOf(opt) != -1 ) {
            $('#rb-' + opt).attr('checked','checked');
            return false;
        }
    });
});
Ties
  • 5,726
  • 3
  • 28
  • 37
0

As already noted in the comments, return false will actually exit the "blog", "user", "forum" loop and thus stop checking the checkboxes once one pathname.indexOf condition is true.

Also you might want to add a console.log(window.location.pathname); to make certain this variable contains what you are checking on. Perhaps it is a casing issue?

If you want to know which literals are present in pathname you could use this:

var isPresent = [];
$( ["blog","user","forum"] ).each(function(num,opt) {
    if ( window.location.pathname.indexOf(opt) != -1 ) {
        $('#rb-' + opt).attr('checked','checked');
        isPresent.push(opt);
    }
});

If you just want to know if one of the literals is present in pathname:

var isAtLeastOneIsPresent = false;
$( ["blog","user","forum"] ).each(function(num,opt) {
    if ( window.location.pathname.indexOf(opt) != -1 ) {
        $('#rb-' + opt).attr('checked','checked');
        isAtLeastOneIsPresent = true;
    }
});
Community
  • 1
  • 1
Laoujin
  • 9,962
  • 7
  • 42
  • 69
0

Solution: the HTML content was not yet written to the page, so now we wait for ajax requests to complete, then we call the function to update the select value, like so...

// apply checked to the selected element
function setAsChecked() {
    $.each(["blog","user","forum"], function(num,opt){
        if (window.location.pathname.indexOf(opt) != -1) {
            $('#rb-' + opt, '.radio_menu').attr('checked','checked');
            return false;
        }
    });
}

// $('.radio_menu').ajaxStop(function(){
//  setAsChecked();
// });

// UPDATE! ajaxStop() catches all our ajax events - not cool. Instead, use when
$.when( $.ajax("") ).done(function(){
    setAsChecked();
});

Maybe that saves someone else a headache!

--- EDIT ---

BE WARNED! This solution caused a major headache when used with CakePHP. The layout disappeared when we called this function in the footer.

See this thread: CakePHP no layout on back and forward button

Community
  • 1
  • 1
Jongosi
  • 2,305
  • 1
  • 28
  • 31