V
V
VaaL20042013-02-14 01:07:57
css
VaaL2004, 2013-02-14 01:07:57

Selecting only one image from several?

Hello, I'm asking for help, I'm new to jQuery, I can't figure it out, so I immediately apologize if the question turns out to be stupid, and the solution is simple.

The bottom line is, there is an online store, it has a product card with a description, photo, and several options (choose the color of the product).

<ul class="options-ul">
<li>
<input id="option-value-265" class="optionlbl" type="radio" value="265" name="option[346]">
<label for="option-value-265">
<img alt="Синий" src="blue-50x50.jpg">
</label>
<label for="option-value-265">Синий</label>
</li>
</ul>


Essence of the question:
How to use jQuery to change the class of the tag to checked when clicking on the image, but when clicking on the second one (there can be several li tags if the product has several color options), the class of the second one changes, and the first one restores the old one.

Somewhere in the depths of Google found a similar solution
<script type="text/javascript"><!--

 $('input[name="option[346]"]:radio').on('change', function() {
    $(this).closest('li').toggleClass('checked');
  });
//--></script>

But in this scenario, by clicking on the checkbox, the class changes to checked, and when you click on the second one, it changes for the second one, but the first one remains unchanged (that is, checked is not removed).

I ask for help, dear audience.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
R
RubaXa, 2013-02-14
@VaaL2004

jsfiddle.net/RubaXa/E9juB/ - demo

$('ul.options-ul').on('change', function (evt){
    // Убираем выделение
    $(this).find('.checked').removeClass('checked', true).prop('checked', false);

    // Добавляем выделение
    $(evt.target).closest('li').addClass('checked');
});

W
WebSpider, 2013-02-14
@WebSpider

For example, you can store the selected item in a variable

var currentElement = null; 
$('input[name="option[346]"]:radio').on('change', function() {
  if (currentElement) currentElement.removeClass('checked');
  currentElement = $(this).closest('li').addClass('checked'); 
}); 

S
spmbt, 2013-02-14
@spmbt

Then elegant is better.

$( function(){
  var selChk = 'li input'; //добавить нужное
  $('ul.class_of_ul').on('change', selChk, function(ev){
  $(ev.delegateTarget).find(selChk).not($(this).addClass('checked') )
    .removeClass('checked').removeAttr('checked');
}); });

D
DanilaMaster, 2013-02-14
@DanilaMaster

It can be like this:

$('ul.options-ul input').on('change', function (){
    $(this).closest('li').addClass('checked').siblings().removeClass('checked');
});

S
sylord, 2013-02-14
@sylord

Perhaps not at all in the topic, but if the checked class is added to li in order to somehow highlight img, then you can use CSS

.optionlbl:checked + label img {

}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question