teamo teamo - 5 months ago 23
CSS Question

Change the class and get values on click in jQuery

I have the following HTML:

<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Changer la devises <span class="caret"></span></a>
<ul class="dropdown-menu dropdown-currency">
<li class="active"><a href="#" id="cad" data-sign="$CAN">Canadian Dollar</a></span></li>
<li><a href="#" id="usd" data-sign="$">American dollar</a></li>
<li><a href="#" id="eur" data-sign="€">Euro</a></li>
<li><a href="#" id="mxn" data-sign="$">Mexican Peso</a></li>
</ul>
</li>
</ul>


On click on any currency, I want to change the active class and get the
id
and the
data-sign
.

What I tried:

$('.dropdown-currency > li > a').click(function(e) {
e.preventDefault();
$('.dropdown-currency > li').removeClass('active');
$(this).addClass('active');
changeCurrency();
});

function changeCurrency() {
var currency = $('.dropdown-currency > li.active > a').attr('id');
var sign = $('.dropdown-currency > li.active > a').data('sign');

alert(currency);
alert(sign);
}


But it doesn't work...

Could you please help me?

https://jsfiddle.net/up1v5j0z/1/

Answer

Try this

$('.dropdown-currency li a').click(function(e) {
    e.preventDefault();
    $('.dropdown-currency li').removeClass('active');
    $(this).parent().addClass('active');
    changeCurrency();
});

function changeCurrency() {
    var currency = $('.active a').attr('id');
    var sign = $('.active a').data('sign');

    alert(currency);
    alert(sign);
}

Fiddle

Comments