I have a select element populated from database, when I select one element, I want to show me some other data from another column related to that row.
For example: on the dropdown I have: apples, bananas, pears
When I select apple I want to select from database the column 'total' that shows me how many apples do I have left.
I think, I should use Javascript-Ajax? Or is it another way to do this with php.
Thanks in advance!
<?php include("db.php"); ?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
$(document).ready(function() {
$('select').material_select();
});
function myFunction() {
if (document.getElementById('selectid').value == "other") {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", "");
x.setAttribute("placeholder", "Write another");
x.setAttribute("class", "input-field col s12");
document.getElementById("myDIV").appendChild(x);
}
}
</script>
</head>
<body>
<div id="myDIV" class="input-field col s4">
<?php
$sql12 = "select * from fruitswhere total>0 && spent=1";
$res1 = mysqli_query($conn, $sql12) or die("Error");
$select = '<select id="selectid" name="name" onchange="myFunction()"><option value = "" disabled selected> Choose </option>';
while($row1 = mysqli_fetch_assoc($res1)) {
$emri = $row1['name'];
// $select.='<option value = "'.$row1['name'].'">'.$row1['name '].'</option>';
$select .= '<option id="my_option" value="'.$name.'">'.$name.'</option>';
}
$select .= '<option value="other">other</option>';
$select .= '</select>';
echo $select;
?>
</div>
<div class="input-field col s4">
<?php
$query2 = "SELECT total FROM fruits WHERE name='$name'";
$res2 = mysqli_query($conn, $query2);
while($row2=mysqli_fetch_assoc($res2)){
$all = $row2['total'];
}
?>
<input name="total" type="number" min="1">
</div>
</body>
</html>