skip to Main Content

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

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search