简体   繁体   中英

how to fill options in html select based on an html field filled by user.

Here is the code snippet :

<select name="isbn" onchange=" ">

<?php

//Displaying all ISBN in drop down
$result = mysqli_query($con,"SELECT * FROM book");
while($row = mysqli_fetch_array($result)) {
?>
    <option> <?php echo $row['ISBN']; ?></option>
<?php } ?>
</select>
</label></td>
</tr>

<tr>
    <td>Copy Number </td>
    <td><select name="copy_number">
<?php

//Now based on selected book I want to fetch number of copies from database
$result = mysqli_query($con,"SELECT number_of_copies FROM book where isbn = [ SELECTE VALUE FROM ABOVE]");
?>

How can I do that?

You can do that with jQuery ajax and simple php handler to get copies of selected book,

<select name="isbn">
.....
</select>

<div id="copies"></div>

<script>

$.ajax({
        url: "getCopies.php?",
        data: "isbn=" + $("select[name='isbn']").val(),
        type: "POST",
        dataType: "json",
        success: function(response) {
            $.each(response, function(i, item) {
                $("#copies").append(item.name); // Sample json format {id: "213123", name:"Lord of the rings", isbn:"887799..."}
            })
        }   

    });

</script>

getCopies.php

<?php

$isbn = $_POST["isbn"];

// Some db connections

$result = mysqli_query($con,"SELECT number_of_copies FROM book where isbn = $isbn");

$resultArr = array();

while($row = mysqli_fetch_array($result)) {
    $resultArr[] = $row;
}

echo json_encode($resultArr); // This will return rows in json format. You can iterate it in js side

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