开发者

Auto populate dropdown based on previous selection [duplicate]

This question already has an answer here: Closed 11 years ago.

Possible Duplicate:

How to dynamically populate options on dropdown lists based on selection in another dropdown?

I have MySQL tables looking like that

regions table

id     |   region
-------------------
1      |   Region1
2      |   Region2

...

and schools table

id     |   school
-------------------
1      |   schno1
1      |   schno5
1      |   schno6
2      |   scho120

There are multiple select (dropdown) menus in my registration form. The regions dropdown looks like that

<td>
<select name="region" id="region">
<option value="">Region</option>
<?php
$result=$db->query("SELECT * FROM regions");
while($row=$result->fetch_array(MYSQLI_BOTH))
{
    echo '<option value="'.$row[0].'">'.$row[1].'</option>';
    }
?>
</select>

</td>
<td>
<div id="sch_dropdown">
<select name="school" id="school">
<option value="">School</option>
</select>
</div>
<span id="loading"><img src="core/design/img/jquery-ui/loading.gif" width="16" height="16" align="absmiddle">&nbsp;Loading...</span>
<div id="no_sch">No schools found</div>
</td>

I want to populate new dropdown list based on previous selections. What i want to do is, get "regions" id, then populate schools dropdown menu based on id (id of previous selection) from "schools" table on the fly. Here is my code but it doesn't work.

My js looks like that

$(document).ready(function(){

function populate() {

       fetch.doPost('core/code/includes/search.php');

}

$('#region').change(populate);

var fetch = function() {

var schools = $('#schools');
return {
    doPost: function(src) {

    $('#loading').show();
    $('#sch_dropdown').hide(); 
    $('#no_sch').hide(); 


        if (src) $.post(src, { region_code: $('#region').val() }, this.getschools);
        else throw ne开发者_开发知识库w Error('No SRC was passed to getCounties!');
    },

    getschools: function(results) {
        if (!results) return;
        schools.html(results);

    $('#loading').hide(); // Hide the Loading...
    $('#sch_dropdown').show(); // Show the drop down
    }   
}
}();

populate();

});

and search.php

if(isSet($_POST['region_code'])) {
$res=$db->query("SELECT * FROM schools  WHERE id='".$_POST['region_code']."'");
while ($row = $res->fetch_array(MYSQLI_BOTH)) {
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
}
}

Please help me to finish it. Thx in advance.


You're calling getschools() with no parameter, so it returns nothing. You were supposed to pass the result that you get after making a POST request to the search.php file.

EDIT: I'm not sure that this will work, as I've not tested it first. But I think you should change

  if (src) $.post(src, { region_code: $('#region').val() }, this.getschools);

to

   if (src) $.post(src, { region_code: $('#region').val() }, function(data){
       getschools(data);
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜