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
To change the text color with jQuery, use the jQuery css() method. The color css property is used to change text color.
$("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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With