I'm to to Javascript and I'm looking to make a form. I found some code that I edited but it doesn't work. What I'm trying to make is a form with 2 select dropdowns. When the visitor chooses one service from the first dropdown, then the 2nd dropdown will be automatically updated with the names of the staff of each service. I have uploded the code to jsFiddle. The url is http://jsfiddle.net/mrtxR/ . I thought it would be really simple but couldn't find any tutorial and guide on this.
// The data that the service should return
// JSFiddle will echo it back for us on that URL
var doctors = {
success: true,
doctors: [
{
id: 71,
name: "George"
},
{
id: 72,
name: "James"
}
]
}
// This is what your JSON from PHP should look like
var jsonDoctors = JSON.stringify(doctors);
console.log(jsonDoctors);
// Bind change function to the select
jQuery(document).ready(function() {
jQuery("#services").change(onServiceChange);
});
function onServiceChange()
{
var serviceId = jQuery(this).val();
$.ajax({
url: '/echo/json/',
type: 'post',
data: {
serviceId: serviceId,
json: jsonDoctors // jsFiddle echos this back to us
},
success: onServicesRecieveSuccess,
error: onServicesRecieveError
});
}
function onServicesRecieveSuccess(data)
{
// Target select that we add the states to
var jTargetSelect = jQuery("#doctors");
// Clear old states
jTargetSelect.children().remove();
// Add new states
jQuery(data.doctors).each(function(){
jTargetSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
});
}
function onServicesRecieveError(data)
{
alert("Could not get services. Please try again.");
}
Your last comment is correct, you should add serviceId to each doctor. Your fake javascript can look like: