Agnes Tom
Agnes Tom

Reputation: 356

Add and remove class on click radio label

I have a list with radio input and text. When I check one it has added a class of checked added to it (this is not in the example). I want to hide the radio and show only text.

I already tried some JS code and I have an almost working sample but there is two things not working well.

The first is that on load of the page any text is marked as active, and second is that the class active is not removed when I click on other text.

$(".attrprod").click(function(e) {
  $(this).addClass("active").siblings().removeClass("active");
});
.active {
  border: 2px solid red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
  <li>
    <label>
      <div class="radio"><span class="checked"><input type="radio" class="attribute_radio" name="group_1" value="954" checked="checked"></span>
      </div>
      <span class="attrprod">36</span>
    </label>
  </li>
  <li>
    <label>
      <div class="radio"><span><input type="radio" class="attribute_radio" name="group_1" value="956"></span></div>
      <span class="attrprod">37</span>
    </label>
  </li>
  <li>
    <label>
      <div class="radio"><span><input type="radio" class="attribute_radio" name="group_1" value="957"></span></div>
      <span class="attrprod">38</span>
    </label>
  </li>
  <li>
    <label>
      <div class="radio"><span><input type="radio" class="attribute_radio" name="group_1" value="958"></span></div>
      <span class="attrprod">39</span>
    </label>
  </li>
  <li>
</ul>

Upvotes: 2

Views: 1185

Answers (2)

mahip_j
mahip_j

Reputation: 368

For first issue add active class to text you want to highlight on page load, like this

<span class="attrprod active">36</span>

For second issue, this line of code might be your problem:

 $(this).addClass("active").siblings().removeClass("active");

You probably want to delete the classes first, then add it to the selected element:

$(".attrprod").click(function (e) {
$(".attrprod").removeClass("active"); // remove all current selections
$(this).addClass("active"); // select this element
});

Upvotes: 1

Zak
Zak

Reputation: 7515

Why not remove all the classes of active first by using attrprod .. And THEN try to set the class via this

$(".attrprod").click(function (e) {
    $(".attrprod").removeClass("active");
    $(this).addClass("active");
});

Upvotes: 1

Related Questions