Search code examples
htmljqueryinnerhtml

jQuery change innerHtml of a group of radio buttons labels with a onClick listener using data-target


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:

  1. all labels in that group of radio buttons to have their innerHtml reset to xxxx
  2. the clicked labels innerHtml set to yyyy

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>


Solution

  • 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.