ngplayground
ngplayground

Reputation: 21667

jquery getting attributes

I have the following code

<a href="#" class="chosenflag" data-flag="<?php echo $lang;?>"><img class="flag" src="/img/flag/United Kingdom.png" alt="" /></a>

<ul class="choices">
<li><a href="#" data-flag="uk"><img class="flag" src="/img/flag/United Kingdom.png" alt="" /></a></li>
<li><a href="#" data-flag="de"><img class="flag" src="/img/flag/Germany.png" alt="" /></a></li>
<li><a href="#" data-flag="es"><img class="flag" src="/img/flag/Spain.png" alt="" /></a></li>
<li><a href="#" data-flag="fr"><img class="flag" src="/img/flag/France.png" alt="" /></a></li>
<li><a href="#" data-flag="it"><img class="flag" src="/img/flag/Italy.png" alt="" /></a></li>
</ul>

The link with the class 'chosenflag' is the active flag which picks up a php variable which will either be uk, de, es, fr, it.

What I would like to happen is somehow get the img src from the ul list to the chosen flag img src depending on the data-flag attribute.

Would someone be able to help me out?

Upvotes: 1

Views: 179

Answers (2)

mraaroncruz
mraaroncruz

Reputation: 3809

This should work if you click on one of the flags. It should put its flag image in the chosen flag image spot.

$chosen = $('.chosenflag')
$('.choices').on('click', 'a', function () {
  // changes data-flag on .chosenflag
  var dataFlag = this.data('flag');
  $chosen.data('flag', dataFlag);
  // 'this' is the clicked on <a>
  var src = this.find('img').attr('src');
  $chosenImg = $chosen.find('img');
  $chosenImg.attr('src', src);
});

I think this is what you are looking for.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382474

To get the choosen flag, do

var flag = $('a.chosenflag').data('flag');

To get the src of the image in a a element of your list having a certain data-flag, do

var src = $('ul a[data-flag='+flag+'] img').attr('src');

Demonstration

Upvotes: 1

Related Questions