-1

In my form I have five radio groups like this:

<label class="radio-inline"><input type="radio" name="persontype1" value="fo" checked="checked">FO</label>
<label class="radio-inline"><input type="radio" name="persontype1" value="po">PO</label>

and then I have a loop to hide/show other elements, based on change event of those radiobuttons:

for (i = 1; i <= 5; i++) {
    $("input[type=radio][name=persontype" + i + "]").change(function() {
        if (this.value == 'fo') {
            $("#person-name" + i).removeClass('hidden');
        }
        else if (this.value == 'po') {
            $("#person-name" + i).addClass('hidden');
        }
    });
}

The problem is that it doesn't work this way. When I use absolute ID value name in the selector, it works:

$("#person-name1").addClass('hidden');

I've tried to use some global variable but it didn't work either. Is there a way how to pass variable i to that function?

Thanks in advance, JiKra

JiKra
  • 1,618
  • 3
  • 29
  • 45
  • 1
    Don't think *"I need five event handlers"*. Think *"I need one event handler that can figure out its context."*. The "closure" duplicate is, technically, the explanation for your trouble, but it's still a red herring. Look at http://pastebin.com/HYX1bz93 – Tomalak Mar 24 '15 at 16:13
  • Good idea, but it doesn't work properly. First radio-change does nothing and others switches the visibility in the opposite way. – JiKra Mar 24 '15 at 16:24
  • That wasn't meant as a copy-and-paste code sample. It was meant as a understand-the-concept code sample. It is *four lines*. I trust you can make the necessary changes. – Tomalak Mar 24 '15 at 16:26
  • Where are the elements that have IDs like `#person-name" + i`? Neither the labels nor the inputs in your example have and ID. – j08691 Mar 24 '15 at 16:37

1 Answers1

0

Wrap the code in an enclosing IIFE (Immediately invoked function expression):

for (i = 1; i <= 5; i++) {
    (function(i){
        $("input[type=radio][name=persontype" + i + "]").change(function() {
            if (this.value == 'fo') {
                $("#person-name" + i).removeClass('hidden');
            }
            else if (this.value == 'po') {
                $("#person-name" + i).addClass('hidden');
            }
        });
    })(i);
}

This will provide a function scope for the inner i (the parameter to the function).

It would make more sense though to use a single event handler and have attributes to determine which is which :)

 // Match on starts-with "persontype" using ^=
 $("input[type=radio][name^=persontype]").change(function() {
     var target = $(this).data('target');
     // Do something to the target
 });
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202