Change tag color with jquery?

I wanted to change the color of the label to red by pressing the button

However, the code does not work, everything seems to be correct

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title> </title> <script type="text/javascript"> function changeColor(id, newColor) { var labelObject = document.getElementById(id); $("#" + id).css("color", newColor); } </script> </head><body> <form id="frm2"> <label for="model">Male</label> <input type="text" name="cars" id="model" /> <br /> <label for="female">Female</label> <input type="text" name="cars" id="color" /> </form> <input type="button" value="Change Label Color" onclick="return changeColor('label', 'red')" /> </body> </html> 

Please, help

+4
source share
3 answers

You pass the โ€œlabelโ€ as the id parameter of your changeColor handler, but there is no element with this identifier in the provided HTML. You will need to add several identifiers to your tags and pass them to the onclick handler. For instance:

 <label for="model" id="label1">Male</label> <input type="text" name="cars" id="model" /> <input type="button" value="Change Label Color" onclick="return changeColor('label1', 'red')" /> 

An alternative would be to pass the identifier of the input element, since they already have the identifiers assigned to them. Then you need to change your changeColor handler as follows:

 function changeColor(inputId, newColor) { $("#" + inputId).prev().css("color", newColor); } 

Edit: Here is jsFiddle demonstrating my second example.

+9
source
 $('input[type="button"]').click(function(){ changeColor('labelCity' , 'red'); }); function changeColor(id, newColor) { $("#" + id).css("color", newColor); } 
+6
source

Here is a simple example to change the label text color to red using jQuery.

  <script src="Scripts/jquery-1.9.0.min.js"></script> <script> $(document).ready(function () { $('#btnChangeColor').click(function () { $('#lbl1').css("color", "red"); }) }) </script> 
 <body> <form id="form1" runat="server"> <label id="lbl1" >Hello friends save girl child</label> <br /><br /><br /> <input type="button" id="btnChangeColor" value="Change Color" /> </form> </body> 
+1
source

All Articles