Vinothini Vinothini - 3 days ago 5
PHP Question

Display tick image when click color for a particular id

I want to display tick image when click one color which is a background color.
My phtml coding is

<?php foreach($this->getSolidColors() as $key => $_solidColors) : ?>
<li id="font-colr-<?php echo $_solidColors['id'] ?>" onclick="selectcolor("<?php echo $_solidColors['id'] ?>");" data-id="<?php echo $_solidColors['id'] ?>" data-img="<?php echo $this->getSkinUrl('css/images/checked.png'); ?>" class="cursor font-color" style="background: #<?php echo $_solidColors['hexa'] ?>" data-color="#<?php echo $_solidColors['hexa'] ?>">
<span class="sprite"></span>
<img id="tick" src="<?php echo $this->getSkinUrl('css/images/checked.png'); ?>" width="80%" height="80%" style="display:none; padding-left:10px;">
</li>
<?php endforeach; ?>


function selectcolor() {
var id = jQuery('#font-colr').attr('data-id');
jQuery('#tick').css('display', 'block');
}


When I click particular color the tick image is displayed for the first color only but I want to get image for which color I clicked and if I select another color the previous tick mark should be disappeared.

Answer

The issue you have is that the id of 'tick' is repeated throughout your page, which is invalid as id must be unique. You should change that to a common class instead.

You should also use unobtrusive JS to attach your event handlers instead of the outdated on* event attributes. Try this:

<?php foreach($this->getSolidColors() as $key => $_solidColors) : ?>
    <li class="cursor font-color" id="font-colr-<?php echo $_solidColors['id'] ?>" data-id="<?php echo $_solidColors['id'] ?>" data-img="<?php echo $this->getSkinUrl('css/images/checked.png'); ?>"  style="background: #<?php echo $_solidColors['hexa'] ?>" data-color="#<?php echo $_solidColors['hexa'] ?>">
        <span class="sprite"></span>
        <img class="tick" src="<?php echo $this->getSkinUrl('css/images/checked.png'); ?>">
    </li>
<?php endforeach; ?>
.tick {
    width: 80%; 
    height: 80%
    display: none; 
    padding-left: 10px;
}
$('li.font-color').click(function() {
    var id = $(this).data('id'); // I presume you use this value somewhere in your code?
    $(this).find('.tick').show();
});
Comments