Search code examples
javascripthtmlinputshow-hide

Javascript change input value when select option is selected


I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:

First Name: <input type="text" value="colors">

<select name="">
   <option>Choose Database Type</option>
   <option onclick="myFunction(g)>green</option>
   <option onclick="myFunction(r)>red</option>
   <option onclick="myFunction(o)>orange</option>
   <option onclick="myFunction(b)>black</option>
</select>

<script>
function myFunction(g) {
    document.getElementById("myText").value = "green";
}
function myFunction(r) {
    document.getElementById("myText").value = "red";
}
function myFunction(o) {
    document.getElementById("myText").value = "orange";
}
function myFunction(b) {
    document.getElementById("myText").value = "black";
}
</script>

Solution

  • A few things:

    You should use the onchange function, rather than onclick on each individual option.

    Use a value attribute on each option to store the data, and use an instance of this to assign the change (or event.target)

    You have no ID on your text field

    You're missing the end quote for your onclick function

    <select name="" onchange="myFunction(event)">
        <option disabled selected>Choose Database Type</option>
        <option value="Green">green</option>
        <option value="Red">red</option>
        <option value="Orange">orange</option>
        <option value="Black">black</option>
    </select>
    

    And the function:

    function myFunction(e) {
        document.getElementById("myText").value = e.target.value
    }
    

    And add the ID

    <input id="myText" type="text" value="colors">
    

    Fiddle: https://jsfiddle.net/gasjv4hs/