簡體   English   中英

動態填充下拉列表,無需重新加載頁面

[英]Dynamically populate dropdown list without reloading page

我有張桌子叫作course 其中包含字段

COURSEID, COURSENAME

另一個名為STUDENTS表。 其中包含

STCODE, STNAME, COURSEID

我已經預載了課程下拉列表。 我想用從第一個下拉列表中選擇的course的學生填充第二個下拉列表,而無需重新加載頁面。

我假設您的第一個下拉菜單具有課程ID的值,除非並且直到這變得復雜為止:

$('select[name=\'course\']').on('change', function() {
    //fetch the course_id of the selected course
    course_id = $('select[name=\'course_id\']').val();

    $.ajax({
      //here sending your data to the file where the function will get your course_id and select students for it and then return it
      url: 'path_to_some_file.php' +  course_id,
      dataType : 'json',
      success: function(json) {
          //this is the success of the ajax. I have returned it in json format but you don't need to. send it in simple array but don't forget to return from the ajax function you called. Below lines is doing nothing but populating your student dropdown and then appending it to the dropdown.

          html = '<option value=""> --- Please Select --- </option>';
          for (i = 0; i < json.length; i++) {
                html += '<option value="' + json[i]['student_id'] + '"';
                html += '>' + json[i]['student_name'] + '</option>';
          }
          $('select[name=\'name_of_your_second_dropdown\']').html(html);

        }
    });
  });

H

您需要進行ajax調用以在更改第一個選擇框時執行此任務。 下面是腳本。 您可能需要包括jquery庫。

  $(document).ready(function()
{

    $('.select').change(function()  // function will work when option will change in select
    {

        var course_id = $('.select').val();
        $.ajax({
        type:"post", 
      url: 'getdetail.php' ,     // url to the php file to get the response 
      data:'course_id='+  course_id,
      success: function(msg) {
          $('.select2').html(msg);

        }
        });
    })
})

html看起來像這樣

<select class="select">
        <option value="1">Course1</option>
        <option value="2">Course1</option>
        <option value="3">Course1</option>  
    </select>

    <select class="select2">
        <option>select1</option>

    </select>

您的php文件將從db獲取數據。 這應該看起來像這樣。 getdetail.php這只是一個示例,根據您的需要和db進行更改。

<?
    $course_id=$_REQUEST['course_id'];     // selected course id here 
    $sql_query="query here " ; // make an sql query to fetch the students from the course.  
    while($result)
    {
        echo "<option value='".$val."'>".$name."</option>"

    }

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM