Jackom
Jackom

Reputation: 436

jQuery - Assign the click function to the radio input

What I would like to do is assign both the checked value and the click function to the radio input located inside the parent div. I currently have this code but it only works for assigning the checked value. The click () function does not work:

<div id="contPosition">
 <div class="contPosition">
 <input type="radio" class="posPrint1" />
 </div>
 <div class="contPosition">
 <input type="radio" class="posPrint2" />
 </div>
 <div class="contPosition">
 <input type="radio" class="posPrint3" />
 </div>
</div>
</div>
</div>

<div id="contPrintPosition">
 <div class="contPrintPosition">
 <input type="radio" class="posPrint1" />
 </div>
 <div class="contPrintPosition">
 <input type="radio" class="posPrint2" />
 </div>
 <div class="contPrintPosition">
 <input type="radio" class="posPrint3" />
 </div>
</div>
</div>
</div>

<script>
jQuery('.contPosition').click(function () {    
    var val =  $(this).find('input:radio').prop('checked')?false:true;
    $(this).find('input:radio').prop('checked', val);
});

//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input').click(function(){
       var curCls = $(this).attr('class');
       $(`.contPrintPosition > input.${curCls}`).val("Test");
});

//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input[type=radio]').click(function(){
    if (this.previous) {
    this.checked = false;
    }
    this.previous = this.checked;                           
});
</script>
      

Upvotes: 1

Views: 42

Answers (1)

Bourbia Brahim
Bourbia Brahim

Reputation: 14702

I dont know what you want to achieve exactly but only one click event could replace all the other event as below snippet :

$(function() {
  //should be ".contPosition input[type=radio]"
  $('.contPosition input[type=radio]').click(function(e) {
    
    var curCls = $(this).attr('class');
    $(`.contPrintPosition > input.${curCls}`).val("Test");
    if (this.previous) {
      this.checked = false;
    }
    this.previous = this.checked;
  });
})
.contPrintPosition input::after {
  content:  attr(value);
  width:100%;
  margin-left:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contPosition">
  <div class="contPosition">
    <input type="radio" class="posPrint1" />
  </div>
  <div class="contPosition">
    <input type="radio" class="posPrint2" />
  </div>
  <div class="contPosition">
    <input type="radio" class="posPrint3" />
  </div>
</div>

<div id="contPrintPosition">
  <div class="contPrintPosition">
    <input type="radio" class="posPrint1" />
  </div>
  <div class="contPrintPosition">
    <input type="radio" class="posPrint2" />
  </div>
  <div class="contPrintPosition">
    <input type="radio" class="posPrint3" />
  </div>
</div>

Upvotes: 1

Related Questions