Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of label using jquery?

I wanted to change the color of the label to Red on button click

However the code isn't working everything seems to be right

    <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

like image 416
vini Avatar asked Aug 04 '12 14:08

vini


People also ask

How to set label text color in jQuery?

To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color.

How can change P tag color in jQuery?

$("p"). on("mouseover", function() { $(this). css("color", "red"); }); Example: In this example, the paragraph element will change to red whenever the user hovers over it.

How to change color in css jQuery?

To change the background color using jQuery, use the jQuery css() property. We will change background color on mouse hover with the jQuery on() and css() method.


1 Answers

You're passing 'label' as the id parameter of your changeColor handler, but there is no element with that ID in the HTML you provided. You'll need to add some IDs to your labels and pass those in the onclick handler. For example:

<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 ID of the input element instead as they already have IDs assigned to them. You would then need to modify your changeColor handler as follows:

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

Edit: Here is a jsFiddle demonstrating my second example.

like image 159
rexmac Avatar answered Oct 26 '22 05:10

rexmac