How do you use Javascript to populate a text box with data based on a select box?

I know a good amount of PHP, but know little about Javascript.

Basically, I want:

If the user selects the x element from the HTML form selection window, then descriptive text for the x element automatically fills in the HTML form text box below it.

Does anyone have a working sample that I can use or edit to be able to do what I need?

+4
source share
3 answers

Here is a working copy in plain JavaScript without using libraries:

<script type="text/javascript">
    // Pre populated array of data
    var myData = new Array();
    myData[1] = 'Some text';
    myData[2] = 'Some other text';
</script>     
<form id="example" name="example">
        <select id="selector" name="selector">
            <option value="" selected></option>
            <option value=1>One</option>
            <option value=2>Two</option>
        </select>
        <br />
        <input type="text" value="" id="populateme" name="populateme" />
    </form>

    <script type="text/javascript">
        document.example.selector.onchange = updateText;

        function updateText() {
          var obj_sel = document.example.selector;
          document.example.populateme.value = myData[obj_sel.value];
    }
    </script>
+9
source

According to the example at http://w3schools.com/js/tryit.asp?filename=tryjs_putmore

<html>
<head>
<script type="text/javascript">
function moveNumbers()
{
var no=document.getElementById("no");
var option=no.options[no.selectedIndex].text;
document.getElementById("result").value=option;
}
</script>
</head>

<body>
<form>
Select numbers:<br />
<select id="no" onchange="moveNumbers()">
    <option>0</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
</select>
<input type="text" id="result" size="20">
</form>
</body>

. http://w3schools.com/htmldom/dom_obj_select.asp http://w3schools.com/htmldom/dom_events.asp .

+2

This will help if the input field has an identifier:

<input type="text" id="someinput" value="" />

Then you need an event listener in the selection box.

<select id="someselect">...</select>

In javascript:

document.getElementById('someselect').onchanged = function() {
var selem = document.getElementById('someselect'); 
document.getElementById('someinput').value = selem.options[selem.selectedIndex].value;
}

This is a very rough idea.

+1
source

All Articles