wataru wataru - 2 months ago 17
PHP Question

Set the li active based on the url

Can someone help me to find what's the problem to my code? Im trying to set the

li
to active based on it's url. But the problem is nothing is set to active after loading. Give me ideas on how to do this or any alternative ways to do this?

NOTE the
$subj_descr
had a space ex.
COMPUTER PROGRAMMING 1
,
ENGLISH 2


here's my php code where the
li
and
a
found.

<li data-popover="true" rel="popover" data-placement="right"><a href="#" data-target=".premium-menu" class="nav-header collapsed" data-toggle="collapse"><i class="fa fa-fw fa-book"></i> Lectures<i class="fa fa-collapse"></i></a></li>
<li><ul id="wa" class="premium-menu nav nav-list collapse in">
<?php
$sql ="SELECT enroll_ref FROM std_enrolled WHERE stud_no = '$stud_no'";
$result = mysqli_query($con, $sql);

while($row = mysqli_fetch_array($result)){
$enroll_ref = $row['enroll_ref'];
}



$sql3 ="SELECT DISTINCT subj_descr FROM subj_enrolled WHERE enroll_ref = '$enroll_ref'";
$results = mysqli_query($con, $sql3);

while($row = mysqli_fetch_array($results)){
$subj_descr = $row['subj_descr'];

?>

<li id="<?php echo $subj_descr; ?>" ><a href="viewlecture.php?subjdescr=<?php echo $subj_descr;?>"><span class="fa fa-caret-right"></span><?php echo ucwords(strtolower($subj_descr)); ?></a></li>
<?php
}
?>
</ul></li>


here's my js

$(document).ready(function() {

$(function(){
var current = location.pathname;
$('#wa li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
});

Answer

Can you try with following code:

$(document).ready(function() {

    $(function(){
        //location.search will give us query string i.e. part present after ? mark and ? itself which is nothing but ?subjdescr=COMPUTER PROGRAMMING 1 
        var current = decodeURIComponent(location.search); //decodeURIComponent to decode white space chars like %20 will get converted to white space 
        alert(current);
        $('#wa li a').each(function(){
            var $this = $(this);

            alert(decodeURIComponent($this.attr('href')));

            // if the current path is like this link, make it active
            if(decodeURIComponent($this.attr('href')).indexOf(current) !== -1){

                $this.closest("li").addClass('active'); //setting the active class to parent li and not to a tag

            }
        })
    })
});

I guess you need to set active to li tag and not to <a> so just grab it via $.closest()

Note: added decodeURIComponent() to avoid encoded chars in string comparision

Comments