Hello!

There are CSS styled buttons in the form of radio switches:

<div class="radio_buttons"> <div> <input type="radio" name="option" id="radio1"/> <label for="radio1" >ВСкст radio ΠΊΠ½ΠΎΠΏΠΊΠΈ β„–1</label> </div> <div> <input type="radio" name="option" id="radio2"/> <label for="radio2">radio ΠΊΠ½ΠΎΠΏΠΊΠ° β„–2</label> </div> <div> <input type="radio" name="option" id="radio3"/> <label for="radio3">Π•Ρ‰Π΅ тСкст radio ΠΊΠ½ΠΎΠΏΠΊΠΈ β„–3</label> </div> <div> <input type="radio" name="option" id="radio4"/> <label for="radio4">radio β„–4</label> </div> </div> 

By default, when you click on <label> checked in input not set. Using jQuery, each button now writes a checked change to something like:

  $("label[for='radio3']").click(function () { $('input:radio[name=option]:nth(2)').attr('checked',true); }); 

In order not to write a separate call function for each button each time, is it possible to automate this process somehow with the help of a cycle or something else?

For example, if the number of buttons is constantly changing, or if there are a large number of buttons.

Thank!

    2 answers 2

    Use .prop("checked") - this reflects the state of the input and does not require additional code on the click of the label element.

     $("button").click(function(e){ alert($("#radio2").prop("checked")); }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <input type="radio" name="option" id="radio1"/> <label for="radio1" >ВСкст radio ΠΊΠ½ΠΎΠΏΠΊΠΈ β„–1</label> </div> <div> <input type="radio" name="option" id="radio2"/> <label for="radio2">radio ΠΊΠ½ΠΎΠΏΠΊΠ° β„–2</label> </div> <br/> <button type="button">Click</button> 

      So what?

       $(function(){ $('label').on('click', function(){ // Π½Π°ΠΉΡ‚ΠΈ блиТайшСго родитСля div, Π² Π½Ρ‘ΠΌ Π½Π°ΠΉΡ‚ΠΈ ΠΈΠ½ΠΏΡƒΡ‚ ΠΈ ΠΏΠΎΡΡ‚Π°Π²ΠΈΡ‚ΡŒ Π΅ΠΌΡƒ 'checked' $(this).closest('div').find('input').prop('checked', true); }) })