Question

Was a bit unsure how else to word this, JavaScript is the main thing I NEED to learn but after putting hours and hours in i still can't write javascript code off the top of my head. I understand the syntax of just about everything but when it comes to integrating it with css or html I am clueless!

Heres the code:

HTML:

<div id="mydiv"> <input type="text" name="colorpicker"> <input type="submit" value="Submit"> </div>

JavaScript:

document.getElementById("mydiv").style.backgroundColor="colorpicker.Submit";

bare in mind i've had little experience with forms and inputs in html too.

Any reply would be much appriciated! Thanks!

Was it helpful?

Solution

The value for style.backgroundColor should be a string representing a color value used in CSS, which can be one of:

  • Color name such as red, green, pink, ...
  • Color hex code such as #ff0000 (or #f00), #00ff00, #ff00ff ...
  • rgb() or rgba() function such as rgb(255,0,0), rgb(0,255,0), ...

You also have to set up the click event handler for the button submit. Here are details:

HTML:

<div id="mydiv">
  <input type="text" name="colorpicker"/>
  <input type="submit" value="Submit"/>
</div>    

JS:

var div = document.getElementById('mydiv');
div.children[1].onclick = function(){
   div.style.backgroundColor = div.children[0].value;
};

Note that you can assign an id for each input field to get access to it in JS code, in the above code I use the children collection to access to them instead. The first input field is the first child of div, the second input field is the second child of div.

Demo

Also note that, since HTML5 (which has been supported by all the major browsers) you can use the color input field which can popup a real color picker dialog for the user to select and then you just need to handle the event onchange to get the selected color (via the value property) like this:

HTML:

<div id="mydiv">
  <input type="color" name='colorpicker'/>    
</div>

JS:

var div = document.getElementById('mydiv');
div.children[0].onchange = function(){
  div.style.backgroundColor = div.children[0].value;
};

Updated Demo.

OTHER TIPS

Use the form tag onsubmit method to call your JavaScript function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top