0

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.

2
  • 1
    Have you tried anything so far? Commented Jan 13, 2016 at 18:23
  • 1
    Totes confusing. Code you have tried? Problems you have had? Commented Jan 13, 2016 at 18:25

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Probably much better than making multiple ajax calls
I cheated a bit and assumed he could pull the data himself :)
its actually working with pre-defined data but how can I use or where can I put my MySql code) from here?
0

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>

2 Comments

'url':'/path_to_php' does this direct to my config file or where?
The path to you .php file. Where ever you are querying MySql for data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.