crozland23
crozland23

Reputation: 35

Change Text Input Values when changing the value of the dropdown menu

I wanted to put a list of users in a dropdown menu taken from MySQL data. Once I selected a user on the menu, I want the values of all the textboxes dynamically change with the values for that user in the MySQL table.

Upvotes: 0

Views: 455

Answers (2)

IrkenInvader
IrkenInvader

Reputation: 4050

Here is a simple example of populating elements based on a dropdown selection. I guessed at your data format but hopefully this will help you get on the right track.

Html

<select id="userDropdown"></select>

<label>Name</label>
<input type="text" id="name" />

<label>Phone</label>
<input type="text" id="phone" />

Javascript

//sql data...
var data = [
    {username: 'User 1', name: 'Bill', phone: '123-456-789'},
    {username: 'User 2', name: 'John', phone: '123-456-987'},
    {username: 'User 3', name: 'Steve', phone: '123-654-789'}
];

var dropdown = $('#userDropdown');
dropdown.append('<option value="" >Select User</option>');
for(var i = 0; i < data.length; i++){
    var item = data[i];
    dropdown.append('<option value="' + item.username + '" >' + item.username + '</option>');
}

$('#userDropdown').change(function(){
    var user = this.value;
    var dataItem = $.grep(data, function(e){ return e.username == user; });

    if(dataItem.length > 0){
        $('#phone').val(dataItem[0].phone);
        $('#name').val(dataItem[0].name);
    }
});

https://jsfiddle.net/c2npt05o/

Upvotes: 1

Kisaragi
Kisaragi

Reputation: 2218

You can use jquery/ajax. Here is an example. You should be able to work from here:

<!--html-->
<select id='name_select'>
        <option value ="john">John</option>
</select>
<input id='name'> 
<script>
     $('name_select').change(function(){
         var name = $('name_select option:selected').val(); //john for example if selected
         $.ajax({
              'url':'/path_to_php',
              'type': 'GET', //or Method: GET, depending you on jquery verion
               'succes': function(returned_data) //php gave a name back
                {
                     $('#name').attr('value',returned_data); // adds 'value' tag to input containing whatever returned data has
               )}
          })
</script>

Upvotes: 0

Related Questions