Gibson
Gibson

Reputation: 2085

Uncheck other radio buttons when checking one, having problems

Im having problems with my UI when selecting radio buttons via click on a div:

I have a loop that shows various radio buttons:

{% for product in collections.regalos.products %}
<li class="grid__item large--one-third gift-card">
  <div class="gift-select-option-inside">
    <input required type="radio" class="gift-input" 
    name="properties[Regalo]" value="{{ product.title }}"> <label>{{ 
    product.title }}</label>
  </div>
</li>
{% endfor %}

I want to apply a class when a radio is checked by toggling it, but it will repeat on every radio input (the other inputs wont disable their class when clicking on a new one)

<script>
  $(".gift-card").on("click", function() {
      var giftradio = $(this).find('input[type=radio]').prop('checked', true);
      giftradio.parent('div').toggleClass('selectedgift');
      $('#builder-t-1').append("<span class='ok'>OK</span>");
  });

   if($('.gift-input').is(':checked')) { alert("it's checked"); }
</script>

Basically, I don't want this: Everything gets duplicated each time I click on a radio. I only need 1 div to be selected and one alert on the tab.

enter image description here

Upvotes: 1

Views: 1140

Answers (2)

Sajib Khan
Sajib Khan

Reputation: 24184

One way is to uncheck all radio button, then select the right one.

<script>
  $(".gift-card").on("click", function() {
    // deselect all 
    $('.gift-input').prop('checked', false).parent('div').removeClass('selectedgift'); 

    var giftradio = $(this).find('input[type=radio]').prop('checked', true);
    giftradio.parent('div').toggleClass('selectedgift');

    $('#builder-t-1').html("<span class='ok'>OK</span>");
  });

  if($('.gift-input').is(':checked')) { alert("it's checked"); }
</script>

Upvotes: 1

Komal Bandi
Komal Bandi

Reputation: 67

I think writing a Jquery script to uncheck is an overkill, instead try the below;

{% for product in collections.regalos.products %}
<li class="grid__item large--one-third gift-card">
  <div class="gift-select-option-inside">
    <input required type="radio" class="gift-input" 
    name="gift-select-checkbox" value="{{ product.title }}"> <label>{{ 
    product.title }}</label>
  </div>
</li>
{% endfor %}

<script>
  $(".gift-card").on("click", function() {
      var giftRadioVal=$('.gift-card :checked').val();
      //Do anything with this val
  });
</script>

Upvotes: 0

Related Questions