Need help with simple javascript

I want to create very simple form:

  1. Input field where I can type color name
  2. Button which I can click and to change body background to the color from input field.
    I know HTML part but have problem with Javascript part.
    Please help.
    Thanks.
    Alex

What part of the JavaScript are you having trouble with?

[list][]obtaining a reference to the button
[
]attaching an event listener to the button
[]getting the colour from the input field
[
]adjusting the background colour
[/list]

Hi Paul,
I can’t get the color from input. This is what I’m trying to do:
document.getElement ById(“buttonid”).onclick = function {
var color = document.getElementById(“inputid”).value;
document.body.style.backgroundColor = “color”;
}
Thanks for quick replay.

Alex

What you are assigning to backgroundColor is the string “color”. If you want to instead refer to the variable called color then the quotes need to be removed from around it.

Yes, you’re right. No quotation marks.
But it still doesn’t work.

Alex

You can’t have a gap in getElement ById. If you could, make up a complete working example of what you have, as explained here: http://www.sitepoint.com/forums/showthread.php?1041498-Forum-Posting-Basics

Hi Ralph,
Sure, no gap, I just typed it here not correct, and also forgot to put () after function.
But I found the way to make it, I put everything in window.onload function.
Now it works, but I want to know professional opinion if this is right way. Here is complete file:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <title>Background color</title>
  </head>
  <body>
    <p>
	  <input type="text" id="color" />
	  <input type="button" id="size" value="Change Color" />
	</p>
	<script>
	   window.onload = function(){
	     document.getElementById("size").onclick = function(){
           var color = document.getElementById("color").value;
           document.body.style.backgroundColor = color;
          }
	    }
	</script>
  </body>
</html>

Thanks.
Alex

Should work fine without that, as long as you place the script where you have it in the code above—just before the closing </body> tag. So this also works fine for me:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <title>Background color</title>
  </head>
  <body>
    <p>
	  <input type="text" id="color" />
	  <input type="button" id="size" value="Change Color" />
	</p>
	<script>
	     document.getElementById("size").onclick = function(){
           var color = document.getElementById("color").value;
           document.body.style.backgroundColor = color;
          }
	</script>
  </body>
</html>

Hi Ralph,
I removed it also and it works perfect.

Thanks.
Alex