I want to trigger a tab to be active when some php conditions are met.
This is the bootstrap code I am using, it is a nav-pills and Toggable / Dynamic.
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<ul class="nav nav-pills">
<li class="active"><a data-toggle="pill" href="#home">Home</a></li>
<li><a data-toggle="pill" href="#menu1">Menu 1</a></li>
<li><a data-toggle="pill" href="#menu2">Menu 2</a></li>
</ul>
<div class="tab-content">
<div id="home" class="tab-pane fade in active">
<h3>HOME</h3>
<p>Some content.</p>
</div>
<div id="menu1" class="tab-pane fade">
<h3>Menu 1</h3>
<p>Some content in menu 1.</p>
</div>
<div id="menu2" class="tab-pane fade">
<h3>Menu 2</h3>
<p>Some content in menu 2.</p>
</div>
</div>
By default Home tab is active. Before the page is loaded, I want to check if a global variable i.e $_SESSION['variable1']
is set. If it is not set, then I should set menu2 to be active.
At the top of the code, I tried doing this and it didn't work
if (!isset($_SESSION['variable1'])){
echo " <script type=\"text/javascript\"> $('.nav-pills
a[href=\"#menu2\"]').tab('show') </script>";
}
But if I inspect element, and paste the JavaScript code above in the console, It work! I can't seem to be able to run it in my code though. Home tab stay active.
</div>
You are executing the script before the HTML is loaded.
I've tried it, and it works if you put the PHP code at the end of the <body>
.
...
</div>
</div>
<?php
if (!isset($_SESSION['variable1'])){
echo " <script type=\"text/javascript\"> $('.nav-pills
a[href=\"#menu2\"]').tab('show') </script>";
}
?>
</body>
Can you try to just add the class using jquery?
<script>
$(document).ready(function(){
<?php
if (!isset($_SESSION['variable1'])){
}?>
$(".tab-pane").removeClass("active");
$("#menu2").addClass("active");
<?php }
?>
});
</script>
hope this will work for you...
I found out how to make it worked.
I did put it at the end of body. Was a stupid mistake I did.
Actually what happenend is the statement always return false.
if (!isset($_SESSION['variable1'])){
echo " <script type=\"text/javascript\"> $('.nav-pills
a[href=\"#menu2\"]').tab('show') </script>";
}
And did not execute the code inside. Because the $_SESSION['variable1'] always has a value as I never cleared it out or destroyed it at some point. I had to use session_detroy()
to initialize everything. And it works like a charm.
Thanks