如何在PHP中的另一个选择标签中调用选择标签ID

时间:2019-01-12 13:46:51

标签: php html

我已经以这种形式创建了一个表单,我希望如果用户从select标签中选择一个元素,那么select标签2应该启用并显示与该元素相关的值。

  <form action="filename.php" method="post" enctype="multipart/form-data" > 
             <?php while($row =mysqli_fetch_array($result)) {?>

   Artist: <?php echo $row['artist'];?>
  <select name="to_artist"  id = "to_artist" class="form-control">
<option value="<?php echo $row['artist'];?>">Select If you want to change</option>
<?php
$sql1 = mysqli_query($con, "SELECT DISTINCT artist_name FROM album");
$row1 = mysqli_num_rows($sql);
while ($row1 = mysqli_fetch_array($sql1)){
echo "<option value='". $row1['artist_name'] ."'>" .$row1['artist_name'] ."</option>" ;
}
?>
</select>
  Album : <?php echo $row['album_name'];?> 

  <select name="to_album"  id = "to_album" class="form-control">
<option value="<?php echo $row['album_name'];?>">Select If you want to change</option>
<?php
$artistname=$_POST['to_artist'];
$sql2 = mysqli_query($con, "SELECT *  FROM album where artist_name='$artistname'");
$row2 = mysqli_num_rows($sql2);

while ($row2 = mysqli_fetch_array($sql2)){
echo "<option value='". $row2['album_name'] ."'>" .$row2['album_name'] ."</option>" ;
}
?>
</select>
  <?php }?> 

  <input type="Submit" value="Submit" name="save" id="save"/>

    </form>

在这段代码中,我希望如果用户选择一个艺术家名称,那么与该艺术家专辑相关的内容将显示在另一个选择标签中,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我建议为此使用jquery并向php进行ajax调用。例如

<script>
$("#to_artist").change(function () {
    var selected_artist= $("#to_artist option:selected").val();

       $.ajax({

                url: "phpfile.php",
                type: "POST",
                data:{artist:selected_artist},
                success: function (response) {
                 //here append response to select box.
                }

            });

});
</script>

<?php 

if(isset($_POST['artist'])){
$artistname=$_POST['artist'];
//here your query to get albums for the selected artist and return them.

$sql2 = mysqli_query($con, "SELECT *  FROM album where artist_name='$artistname'");
$row2 = mysqli_num_rows($sql2);

while ($row2 = mysqli_fetch_array($sql2)){
echo "<option value='". $row2['album_name'] ."'>" .$row2['album_name'] ."</option>" ;
}

}


?>

///您可以在选择框内创建一个div,并在其中添加选项。

例如

 <select>
      <div id="appended-options">

     </div>
     </select>

  use this in jquery : $("#appended-options").append(response);