2

I'm trying to make the text field change its color but it doesn't seem to work Here is the code:

<html>
<head>
  <title>   
  This is a title
  </title>

<script type="text/javascript">
    function changeColor()
    {
    alert("bla")
    document.getElemenyById("text1").style.background-color:red;
    }
</script>
</head>

<body>

<form>
<input id="text1" type="text" onkeypress="changeColor()">
</form>


</body>

</html>
  • thank you
Dani Gilboa
  • 599
  • 4
  • 13
  • 30

4 Answers4

4

That's a syntax error. You can't use CSS syntax (background-color: red) inside JavaScript.

You want to actually assign a value (the string "red") to a member of the style object called backgroundColor:

...style.backgroundColor = "red";
user229044
  • 232,980
  • 40
  • 330
  • 338
3

Try this:

document.getElementById("text1").style.backgroundColor = "red";

Demo: http://jsfiddle.net/jG95a/

There were four problems in your code:

  • A typo in getElementById() (you had a "y" instead of a "t")
  • background-color is not valid in JS dot notation, you need backgroundColor
  • You need = not :
  • red needs to be a string, "red"

Or to put those last three points another way, the way you had background-color:red is appropriate in a stylesheet, but not in JavaScript.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

If using Jquery use CSS() . If Plain Javascript

document.getElementById("text1").style.backgroundColor = "red";

or

document.getElementById("text1").style("backgroundColor":"red"); 

One error is in "getElementById" typo

2

1) most of CSS attributes accessed from JavaScript need to replace all "-" and use rpn style, ie.

background-color becomes backgroundColor,

border-collapse becomes borderCollapse and so on.

2) When manipulating styles in JavaScript one may often need to update multiple attributes at once. A good and elegant method is to use the JavaScript "with" statement :

with(document.getElementById("text1").style) {
    backgroundColor = 'red' ;
    fontWeight = 'bold' ;
    // etc... 
} 

3) the jQuery way is also simple :

$('#text1').css({
    "background-color": "red", 
    "font-weight": "bold"
}) ;

http://api.jquery.com/css/

Samuel-L-29
  • 175
  • 1
  • 9