Amit
Amit

Reputation: 22086

How to change background color of TextBox by Javascript?

I am trying to change background color of textbox by using javascript but my code is not working. I search SO but not find any suitable answer. Here is my code.

<head>
    <script type="text/javascript" language="javascript">
        function abc() {
            var v = document.getElementById("<%=TextBox1.ClientID%>");
            v.setAttribute('BackColor', 'Red');
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="abc()" onclick="Button1_Click"/>
    </div>
    </form>
</body>

enter image description here

Upvotes: 0

Views: 24554

Answers (2)

Galled
Galled

Reputation: 4206

You are trying to change the UI that is html, so you need to use javascript/css properties.

Here there is a list of css attributes accessible by javascript.

Try with:

   <script type="text/javascript" language="javascript">
        function abc() {
            var v = document.getElementById("<%=TextBox1.ClientID%>");
            v.style.backgroundColor = "red";
        }
    </script>

Furthermore I have the Visual Studio 2010 and the Intellisense also show me the style attribute:

enter image description here

You are right jams, when I pretend to point to an id from a html generated by asp the intellisense doesn't works for the style attribute:

enter image description here

enter image description here

I think the Intellisense doesn't reach to this id because at the moment of you are writting this code, the html doesn't exists.

Upvotes: 7

vcsjones
vcsjones

Reputation: 141703

BackColor does not exist on the client side. That's an ASP.NET server-side notion. Rather, you want to set it with CSS:

v.style.backgroundColor = 'Red';

Here is a reference of the names of CSS properties as they would appear in JavaScript.

Upvotes: 2

Related Questions