I try to write a function with radio buttons, but for some reason the script does not work.

<input type="radio" name="test" class="input_1"> <input type="radio" name="test" class="input_2"> <span class="test_1"></span> 

Like this:

  <script> $('input.input_1').change(function(){ if( $('.input_1').change ) { $('span.test_1').addClass('style_1'); } else { $('span.test_1').text('style_2'); } }); </script> 

What's my mistake?

  • what exactly is not working? in the example of markup, there is no element anywhere with the class input_1 - Grundy
  • Thanks, corrected. - Frontendman

1 answer 1

input type="radio" - works like a button, so we will use the click event. The if( $('.input_1').change ) check does not make sense, since it checks for the jQuery-wrapper's change method and always returns true .

Looks like you need something like:

 $('input[name="test"]').click(function(){ $('input[name="test"]').each(function(){ $('span.test_1').removeClass($(this).data("spanclass")); }); $('span.test_1').text($(this).data("spanclass")); $('span.test_1').addClass($(this).data("spanclass")); }); 
 .style_1{ color:red; } .style_2{ color:green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="test" class="input_1" data-spanclass="style_1"> <input type="radio" name="test" class="input_2" data-spanclass="style_2"> <span class="test_1"></span> 

  • and where is the explanation? - Grundy
  • @Grundy a minute. - Igor