Christien
Christien

Reputation: 120

How to simplify and fix this radio button like function in jQuery?

I am looking for a way to make two blocks of code just one block. How can I do this? I have been trying, but I don't know how to target the children from only one container at a time.

How can I solve this?

values = (function () {

  var valueOne = '.block-v1';
  $(valueOne).each( function(index) {
    $(this).click(function () {
      if ($(this).hasClass('active')) {
      } else {
        $(valueOne).removeClass('active')
        $(this).addClass('active');
      }

      var number1 = $(this).attr("data-nub");
      test(number1)

    });
  });

  var sub = '.block-v2';
  $(sub).each( function(index) {
    $(this).click(function () {
      if ($(this).hasClass('active')) {
      } else {
        $(sub).removeClass('active')
        $(this).addClass('active');
      }

      var number2 = $(this).attr("data-nub");
      test(number2)
    });
  });


  test = (function (number1, number2) {
    $('.nub-result-target').html(number1 + number2);
  });

})(this, jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="blocks">
  <div id="one" data-nub="1" class="block block-v1 active">block-v1 1</div>
  <div id="two" data-nub="2" class="block block-v1">block-v1 2</div>
</div>

<div class="blocks sub">
  <div id="sub-one" data-nub="3" class="block block-v2">block-v2 1</div>
  <div id="sub-two" data-nub="4" class="block block-v2 active">block-v2 2</div>
</div>

<div class="blocks nub-result">
  <div class="nub-result-values">numbers: <span class="nub-result-target">temp</span>
  </div>
</div>

Upvotes: 0

Views: 34

Answers (1)

Zoltan Toth
Zoltan Toth

Reputation: 47667

values = (function () {
  var number1 = $('.block-v1.active').attr('data-nub'),
      number2 = $('.block-v2.active').attr('data-nub');

  $('.block').each( function(index) {
    $(this).click(function () {
      var val = $(this).attr('data-nub');

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

      if ($(this).hasClass('block-v1')) {
        number1 = val;
      } else {
        number2 = val;
      }

      $('.nub-result-target').html(number1 + number2);
    });
  });
})(this, jQuery);
.active {
  background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="blocks">
  <div id="one" data-nub="1" class="block block-v1 active">block-v1 1</div>
  <div id="two" data-nub="2" class="block block-v1">block-v1 2</div>
</div>

<div class="blocks sub">
  <div id="sub-one" data-nub="3" class="block block-v2">block-v2 1</div>
  <div id="sub-two" data-nub="4" class="block block-v2 active">block-v2 2</div>
</div>

<div class="blocks nub-result">
  <div class="nub-result-values">numbers: <span class="nub-result-target">temp</span>
  </div>
</div>

Upvotes: 1

Related Questions