I want to get data-value where the class is active. when I am clicking on nav-tabs it alerting undefined How can I resolve this error? Please help me.
HTML:
<ul class="nav nav-tabs">
<li class="active" data-value="buy"><a data-toggle="tab" href="#home">BUY</a></li>
<li data-value="rent"><a data-toggle="tab" href="#home">RENT</a></li>
<li><a href="Post_Property.html">SALE</a></li>
</ul>
jQuery:
$(".nav-tabs").click(function(){
alert($(".active").attr("data-value"));
})
$('.nav-tabs').on('shown.bs.tab', function (e) { alert($(".active").attr("data-value")); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <ul class="nav nav-tabs"> <li class="active" data-value="buy"><a data-toggle="tab" href="#home">BUY</a></li> <li data-value="rent"><a data-toggle="tab" href="#home">RENT</a></li> <li><a href="Post_Property.html">SALE</a></li> </ul>
I had updated the changes in the code u can use shown.bs.tab method for bootstrap.
You can get data attribute like:
$(".active").data("value");
it will return the data-value
and in your case the DOM is not properly traversed. The proper code is:
$(".nav-tabs").click(function(){
alert($(this).find(".active").data("value"));
})
as .active
is the child of .nav-tabs
, so you have to traverse it.
Simply traverse and get the active tag, like this:
$(".nav-tabs").click(function(){
alert($(this).find(".active").attr("data-value"));
});
Also, instead of attr('data-value')
, you can use data("value")
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.