Skip to content
Advertisement

Fetch value from Database and fill all textbox if dropdown value change

I am trying to fill all textbox value depend on dropdown value selection. And I also fill dropdown value by SQL query. Here is HTML Code:

<select name="name" ID="name" class="form-control">
<option value="Select">Select</option>
<?php
$qu="Select DISTINCT Cname from Client_table";
$res=mysqli_query($con,$qu);
while($r=mysqli_fetch_row($res))
{ 
    echo "<option value='$r[0]'> $r[0] </option>";
                                            
}
?> 
</select>
<label>Address</label><input type="text" name="add"/>
<label>Contact</label><input type="text" name="con"/>

DataBase:

  Client_table
   C_no             Cname           Caddress          Ccontact
    1               Mohit             xyz             0123645789
    2               Ramesh            abc             7485962110

Here I am confused that how to find address and contact of a client based on dropdown selection and fill textbox with this values

Advertisement

Answer

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="stack";
// Create connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);


$qu = "SELECT DISTINCT Cname,Caddress,Ccontact FROM Client_table";
$res = $conn->query($qu);
?>
<select name="name" ID="name" onchange="myFunction()" class="form-control">
<option value="Select">Select</option>
<?php

while($r = mysqli_fetch_row($res))
{ 
    echo "<option data-add='$r[1]'  data-con='$r[2]'  value='$r[0]'> $r[0] </option>";
}
?> 
</select>
<label>Address</label><input type="text" name="add" id="add"/>
<label>Contact</label><input type="text" name="con" id="con"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>


    function myFunction(){
        var address = $('#name').find(':selected').data('add');
        var contact = $('#name').find(':selected').data('con');
        $('#add').val(address);
        $('#con').val(contact);
    }
</script>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement