John John - 5 months ago 22
HTML Question

How to get value from onclick() Button to input jquery

i am trying to create a color picker, whenever i click on a colored button, the respective color name gets sent to the input automatically; if i click on white button i get in input : White and so on ...
Here is my code so far:

HTML


Color:


<td width="314"><input name="white" type="button" id="white" onclick="changewhite()" value="" width="20px" />
<input name="black" type="button" id="black" onclick="changeblack()" value="" width="20px" />
<input name="red" type="button" id="red" onclick="changered()" value="" width="20px" />
<input name="blue" type="button" id="blue" onclick="changeblue()" value="" width="20px" />
<input name="yellow" type="button" id="yellow" onclick="changeyellow()" value="" width="20px" />



JavaScript

function changewhite() {
document.getElementById("color").innerHTML="White";
}
function changeblack() {
document.getElementById("color").innerHTML="Black";
}
function changered() {
document.getElementById("color").innerHTML="Red";
}
function changeblue() {
document.getElementById("color").innerHTML="Blue";
}
function changeyellow() {
document.getElementById("color").innerHTML="Yellow";
}


NB:
I would like to add that before using an input to get the color, i was using
<p id="color"> </p>
, the code was working perfectly, but don't know why with an input it didnt work.

Kld Kld
Answer

To change the input value use the .value not .innerHtml , You should also use the same function for all the inputs

function changeColor(element) {
    document.getElementById("color").value = element.name;
}
input#black {
  background-color: black;  
}

input#blue {
  background-color: blue;  
}

input#red {
  background-color: red;  
}

input#white {
  background-color: white;  
}

input#yellow {
  background-color: yellow;  
}
<input name="white" type="button" id="white" onclick="changeColor(this)" value="" width="20px"  />
<input name="black" type="button" id="black" onclick="changeColor(this)" value="" width="20px" />
<input name="red" type="button" id="red" onclick="changeColor(this)" value="" width="20px" />
<input name="blue" type="button" id="blue" onclick="changeColor(this)" value="" width="20px" />
<input name="yellow" type="button" id="yellow" onclick="changeColor(this)" value="" width="20px" />
  
  
<input type="text" id="color"  />