简体   繁体   中英

How to call select tag id in another select tag in php

I have created a form in that form I want that if the user selects one element from select tag then select tag 2 should enable and shows the value related to that element.

  <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>

In this code, I want that if the user selects an artist name then related to that artist albums will be shown in another select tag can anyone help me?

I recommend to use jquery for that and make an ajax call to php. For example

<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>" ;
}

}


?>

//you can create a div inside select box where you would like to append options.

Ex.

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

     </div>
     </select>

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

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