I know how to select / activate (programmatically) a tab in materializecss using jquery(as mentioned in documentation):
$('ul.tabs').tabs('select_tab', 'tab_id');
But how to get an id of an active(selected) tab in materializecss using javascript or jquery when I click a button?
I know how to select / activate (programmatically) a tab in materializecss using jquery(as mentioned in documentation):
$('ul.tabs').tabs('select_tab', 'tab_id');
But how to get an id of an active(selected) tab in materializecss using javascript or jquery when I click a button?
Share Improve this question asked Dec 20, 2016 at 4:04 oentorooentoro 7501 gold badge11 silver badges33 bronze badges4 Answers
Reset to default 5You can use the active class to get the current active tab. And hence can get the id of the current tab. Below is a demo
$(document).ready(function(){
$('ul.tabs').tabs();
});
$('#getID').click(function(){
console.log("Active Tab:"+$(".active").attr('id'));
console.log("Active Tab Div:"+$(".active").attr('href'));
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/materialize/0.97.8/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare./ajax/libs/materialize/0.97.8/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<ul class="tabs">
<li class="tab col s3"><a href="#test1" id="1test">Test 1</a></li>
<li class="tab col s3"><a class="active" href="#test2" id="2test">Test 2</a></li>
<li class="tab col s3"><a href="#test4" id="4test">Test 4</a></li>
</ul>
</div>
<div id="test1" class="col s12">Test 1</div>
<div id="test2" class="col s12">Test 2</div>
<div id="test3" class="col s12">Test 3</div>
<div id="test4" class="col s12">Test 4</div>
</div>
<button id="getID">
GetID
</button>
Although above techniques might be ok there is official way to do it in materializecss.:
$('ul.tabs').tabs({
onShow: onShow,//Function to be called on tab Show event
swipeable: false,
responsiveThreshold: Infinity // breakpoint for swipeable
});
function onShow(tabOBJ){
console.log(tabOBJ.selector);
}
I hope this might help you and others.
You can use jquery. As the active tab will has the class active
you can use it for getting the tab id.
$(function(){
$('#submit').click(function(){
alert($(".active").attr('id'));
});
});
A working fiddle here http://jsfiddle/UTux2/
try this
$("ul.tabs > li > a").click(function (e) {
var id = $(e.target).attr("href").substr(1);
window.location.hash = id;});
var hash = window.location.hash;
$('ul.tabs').tabs('select_tab', hash);
make hash id first then place that in place tab_id