Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 677
Citizen Avatar asked Dec 14 '22 02:12

Citizen


2 Answers

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>
like image 71
Rob Booth Avatar answered May 11 '23 01:05

Rob Booth


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.

like image 24
jrummell Avatar answered May 11 '23 01:05

jrummell