String or jQuery.each object

Why is this not working?

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

When I enter $('#rb-blog').attr('checked','checked'); Does it work as expected?

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

--- UPDATE ---

I just saw that html is written to the page via ajax and executed on .ready() :( Thanks for the help, which is very appreciated.

+1
source share
3 answers

Solution: HTML content has not yet been written on the page, so now we are waiting for ajax requests to complete, then we call a function to update the selection value, for example ...

 // 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(); }); 

Perhaps this will save someone else from a headache!

--- EDIT ---

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

See this topic: CakePHP without back and forth button layout

0
source

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

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

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

You can also add console.log(window.location.pathname); to make sure that this variable contains what you are checking. Perhaps this is a problem with the case?

If you want to know what literals are present in pathname, you can 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 find out if one of the literals is present in the path name:

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

Source: https://habr.com/ru/post/893184/


All Articles