I have multiple groups of radio buttons. Names and Id's dynamically via variables. Each radio button has a label that I use (via css) as a button instead of the radio button itself (hidden).
when I click on a label, I need two things to happen:
The second part I can do. Its the first part I have trouble with. Maybe there is need to do it as a loop? But anyway, tried it with a single radio button first, couldn't make it work
$(document).on('click', '.n', function() {
$('label[for^=$(this).data("target")]').html("xxxx");
$("#" + $(this).data("target") + "label").html("yyyy");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="1" name="na" value="" />
<label for="1" data-target="1" id="1label" class="n" selected>yyyy</label>
<input type="radio" id="2" name="na" value="" />
<label for="2" data-target="2" id="2label" class="n">xxxx</label>
<input type="radio" id="3" name="na" value="" />
<label for="3" data-target="3" id="3label" class="n">xxxx</label>
Please check below, hope it is clear:
$(document).on('click', '.n', function() {
var thisLabel = $(this);
var thisDataTarget = thisLabel.data('target');
var thisTarget = $('#'+thisDataTarget);
var thisGroupName = thisTarget.attr('name');
$('input[name='+thisGroupName+']').each(function(i) {
var loopInput = $(this);
var loopID = loopInput.attr('id');
var loopText = loopID==thisDataTarget ? 'yyyy' : 'xxxx';
$('label[for='+loopID+']').html( loopText );
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="1" name="na" value="" />
<label for="1" data-target="1" id="1label" class="n" selected>yyyy</label>
<input type="radio" id="2" name="na" value="" />
<label for="2" data-target="2" id="2label" class="n">xxxx</label>
<input type="radio" id="3" name="na" value="" />
<label for="3" data-target="3" id="3label" class="n">xxxx</label>
Also on JSFiddle.