简体   繁体   中英

How to change <option> of a 3rd <select> based on change in 2nd <select>, where 2nd is drawn by changing value of 1st dropdown using jquery ajax

I got a little weird situation in my project (for a school management) and could not find a suitable solution for it on internet. here is the problem, I have three <select> element, the first is to select class, second one is to select section in that class and third one is to select course from that section. the code is as following

<select id="class">
    <option value="class1">Class 1</option>
    <option value="class2">Class 2</option>
</select>


<select id="section">
    <!--sections will be drawn here from database using ajax, based on class selected in 1st dropdown-->
</select>


<select id="course">
    <!--when a section is selected in 2nd dropdown, courses of that section will be drawn here from database using ajax-->
</select>

my ajax code to draw #section when change #class is following, it simply take the selected class and send it to draw_sections.php, where I used $_GET[] to get its value and used it in a query to select sections of that class from database

$("#class").change(function(){
   var class = $(this).val();
   $.ajax({
       url: "draw_sections.php?class="+class+"", success: function(sections) {
         $("#section").html(sections);
       } 
    });
});

Till this point, it works fine and draws the sections of selected class. Now i want to draw courses in 3rd drop down <select> when a section is selected in 2nd <select> . here is ajax my ajax code

$("#section").change(function(){
       var section = $(this).val();
       $.ajax({
           url: "draw_courses.php?section="+section+"", success: function(courses) {
             $("#course").html(courses);
           } 
        });
  });

this function was intended to take section (like it did in class) to draw_course.php and select courses of that section from database and then draw it in 3rd drop down (as it did in first drop down ie class) but the problem is as the sections are drawn through ajax, selecting a section does not affect the course drop down. also the sections do not exist in source code. as I am beginner with ajax, so could not explain my problem better than this.

Try jQuery .on

  $("#section").on('change',function(){
      //code here
    });

YOu need to use either delegate or on since the select boxes are build dynamically

$("body").delegate('#section','change',function(){
  //code
});

Or

$("#section").on('change',function(){
//code
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM