Change color of label using jquery?
Asked Answered
S

3

5

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

Sinuate answered 4/8, 2012 at 14:29 Comment(1)
where is a control with LabelCity in the markup ?Antechamber
P
13

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.

Portia answered 4/8, 2012 at 14:47 Comment(1)
I like the 2nd example, with the .prev() approach, because it avoids having to assign ids to each label. Saves work, and more importantly improves maintainability, on large forms.Lyn
M
8
$('input[type="button"]').click(function(){
     changeColor('labelCity' , 'red');
}); 

function changeColor(id, newColor) {

   $("#" + id).css("color", newColor);

}  
Mcconaghy answered 4/8, 2012 at 14:34 Comment(0)
A
2

Here is a simple example to change the color of a label text 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>
Automatic answered 19/10, 2015 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.