Skip to content Skip to sidebar Skip to footer

Populate Two Different Combo Boxes Using Ajax At A Time

I have 3 combo box: Department, Courses, Activities. The Department combo box which will load all departments from the department table. I need to load the courses in one combo box

Solution 1:

You can do something like this :

$('#department_combo').change(function(){
    $.ajax({
        url: "/someUrl/courses",
        success: function(data) {
            // Populate courses with data
        }
    });
    $.ajax({
        url: "/someUrl/activities",
        success: function(data) {
            // Populate activities with data
        }
    });
});

Solution 2:

Since the activities and courses are department specific I would do one ajax request that returns the courses and activites for a specific department in an JSON object that may look something like this when the uses selected dept 1:

{
courses : [
    {cid:1,course:'abc'},
    {cid:2,course:'xyz'},
    {cid:3,course:'prq'}],
activities : [
    {aid:1,activity:'foo1'},
    {aid:2,activity:'foo2'},
    {aid:3,activity:'foo3'}]
}

and this when the user selected dep2:

{
courses : [
    {cid:4,course:'bar'},
    {cid:5,course:'foo'}],
activities : [
    {aid:4,activity:'bar1'},
    {aid:5,activity:'bar2'}]
}

so on the change event of your department dropdown your event handler would make your ajax request and fill the activity and course dropdown with the results returned from the server.

$('#department').change(function(){
    $.ajax(
       url: 'urlToYourServersideCode',
       success: function(coursesAndActvities){
           var courses = coursesAndActivies.courses,
               activites = coursesAndActivies.activities,
               sCourses='',
               sActivies = '';
           for(var idx = 0;idx < activities.length;++idx){          
               sActivities+= '<option value="'+ activities[idx].aid +'">' + activities[idx].activity +'</option>';

           }
           for(var idx = 0;idx < courses.length;++idx){         
               sCourses+= '<option value="'+ courses[idx].aid +'">' + courses[idx].course+'</option>';

           }
           $('#activities).empty().append(sActivities);
           $('#courses).empty().append(sCourses);
       }
 );
});

Post a Comment for "Populate Two Different Combo Boxes Using Ajax At A Time"