4

when i did click text input, i want to change input background color but with javascript.

I know with css.

I want for example.

<form action="" name="abc" method="post">
<input name="abc" id="name" type="text"/>
<input name="yusuf" type="text"/>
<input type="submit"/>
</form>

How can i select element name as name with javascript?

I want similar:

 <script>
document.getElementById("name").style = "background-color:red";
</script>

I want to write css code but direct. Shortly how can i reach style="" parameters?

5
  • 2
    better to use jquery lib, than pure js Commented Aug 28, 2011 at 13:19
  • sorry. i did find. document.getElementById("name").setAttribute("style",'background:red;'); @Marek Sebera. Thanks for proposal. I know jquery but i want to learn with javascript. Commented Aug 28, 2011 at 13:20
  • 1
    have you thought about using jQuery, MooTools or Prototype? It makes this sort of stuff really easy. Commented Aug 28, 2011 at 13:20
  • thanks fro proposal.. @gargantaun.. Commented Aug 28, 2011 at 13:24
  • Check out my jQuery solution below, with working sample. Another question would be: what's the reason for this behavior? Are you doing some kind of validation? If so, jQuery validate is a very complete solution. Commented Aug 28, 2011 at 13:38

2 Answers 2

6

You're looking for the style object:

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

You can also set the className property to apply an existing CSS class to the element.

Sign up to request clarification or add additional context in comments.

Comments

2

Is jQuery an option? You can try something like this:

$(document).ready(function(){
    var toggleRed = function(){
        $(this).toggleClass('red');
    };
    $('input[type=text]').focus(toggleRed);
    $('input[type=text]').blur(toggleRed);
});

And then define this in your CSS:

input.red { background-color: Red; color: White; }

Check out the working example: http://jsfiddle.net/V5qJp/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.