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
-
1Have you tried anything so far?silhouette hustler– silhouette hustler2016-01-13 18:23:13 +00:00Commented Jan 13, 2016 at 18:23
-
1Totes confusing. Code you have tried? Problems you have had?Jay Blanchard– Jay Blanchard2016-01-13 18:25:14 +00:00Commented Jan 13, 2016 at 18:25
Add a comment
|
2 Answers
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);
}
});
3 Comments
Kisaragi
Probably much better than making multiple ajax calls
IrkenInvader
I cheated a bit and assumed he could pull the data himself :)
crozland23
its actually working with pre-defined data but how can I use or where can I put my MySql code) from here?
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
crozland23
'url':'/path_to_php' does this direct to my config file or where?
Kisaragi
The path to you
.php file. Where ever you are querying MySql for data.