<script> $('input[type=radio]').click(function(event){ $("label").css({ 'background-color' : 'white' }) }); </script> 

There is such a simple script, which when selecting an input, highlights the inscription next to it. But this script highlights all the labels on the page. How to make so that only that label which is pressed by the user was highlighted?

HTML has this structure.

 <form> <label> <input type="radio" />_ Sample text_</label> </form> 
  • This is a css task - Serge Esmanovich
  • and tell me, why is jquery here? - Stranger in the Q

2 answers 2

 $(document).ready(function() { $('input[type=radio]').click(function(event) { $(this).closest("label").css({ 'background-color': 'red' }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label> <input type="radio" />_ Sample text_ 1</label> <label> <input type="radio" />_ Sample text_ 2</label> <label> <input type="radio" />_ Sample text_ 3</label> </form> 

  • For some reason it does not work. HTML has this structure. <form> <label> <input type="radio" />_ Sample text_</label> </form> Wrapped in a div and everything together and separately. does not work ... - Bim Bam

To correct the current code, instead of $('label') , which selects all labels on pages, you need to take the container of the element you clicked on, in this case, click on radio, which is inside the label, therefore it is enough to take $(this).parent()

 $('input[type=radio]').click(function(event) { $(this).parent().css({ 'background-color': 'red' }) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <label><input type="radio" />_ Sample text_</label> </form>