Citizen
Citizen

Reputation: 12937

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

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

Basically, what I want is:

If a user selects item x from an HTML form select box, then the descriptive text for item x will auto populate an HTML form input text box below it.

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

Upvotes: 4

Views: 58017

Answers (3)

Rob Booth
Rob Booth

Reputation: 1782

Here is a working copy in plain JavaScript using no 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>

Upvotes: 9

James Black
James Black

Reputation: 41858

It would help if the input box has an id:

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

Then you need an event listener on the select 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.

Upvotes: 1

jrummell
jrummell

Reputation: 43077

Based on 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>

See http://w3schools.com/htmldom/dom_obj_select.asp and http://w3schools.com/htmldom/dom_events.asp for more info.

Upvotes: 3

Related Questions