选择列表选择后生成数据

时间:2013-05-16 17:24:54

标签: php sql selection populate

假设我有一个带有邮政编码字段(text)和学校字段(selection)的表单,目前我可以使用数据库中的学校名称填充选择列表但是我希望与所选学校链接的邮政编码自动填充:

<?php

$conn = mysqli_connect("localhost", "twa312", "dam6av9a");
mysqli_select_db(twa312, $conn)
or die ('Database not found ' . mysqli_error() );

$options = '<option value="0"></option>';

$sql = "SELECT school_info.name AS name, local_schools.postcodeID AS postcode FROM school_info INNER JOIN local_schools ON local_schools.schoolID = school_info.schoolID";
$rs = mysqli_query($sql, $conn)
or die ('Problem with query' . mysqli_error());

1 个答案:

答案 0 :(得分:0)

我可以看到两种可能的解决方案。生成javascript数组,其中学校ID为密钥,邮政编码为值。并且在选项更改时相应地设置后期字段值。或者使用ajax从数据库加载它。

例如,您可以生成以下内容:

<script> 
    var postcode_list = JSON.decode('<?php echo json_encode($postcode_array);?>');
    // put this function inside select on change method
    // also if you load default value you can add to onload method
    function update_postcode(){
        var select_val = jQuery("#primary").val();

        var postcode = postcode_list['+ select_val +'];

        //checking if we have such value
        if(typeof postcode != 'undefined'){
            jQuery("#post").val(); 
        }
</script>

代码可能无效,未经过测试。