aziz aziz - 5 months ago 12
PHP Question

Select onchange update other input fields

I have a form with one Select option and 3 input text box. I fetch the value of select option from database. I want to change data of the 3 input field based on what i select. I try many ways but faild.

<Select onchange="update(this)">
<?php
$query = "SELECT * FROM wheel1 ORDER BY chair_no ASC";
$run = mysqli_query($connect, $query);
$i = 0;
while ($chair = mysqli_fetch_assoc($start)) {
$i++;
?>
<option value="<?php echo $chair['chair_no'];?>"><?php echo $i ?></option>
<?php
$name = $chair['name'];
$phone = $chair['phone'];
$detail = $chair['detail'];
}
?>


It fetch data perfectly for Select menu, But only store the last value for name phone and detail variable. Here is javascript code.

function update( elem ) {
var name = "<?php echo $name; ?>";
var phone= "<?php echo $phone; ?>";
var detail = "<?php echo $detail; ?>";
document.getElementById("name").innerHTML = name;
document.getElementById("phone").innerHTML = phone;
document.getElementById("detail").innerHTML = detail;
}


Any help is appricated. Thanks in advance.

Answer

Set diffident attribute in options for name, phone and detail

Demo: https://jsfiddle.net/sjhhv4pw/

<select onchange="update(this)">
<?php 
    $query = "SELECT * FROM wheel1 ORDER BY chair_no ASC";
    $run = mysqli_query($connect, $query);
    $i = 0;
    while ($chair = mysqli_fetch_assoc($start)) {
    $i++;
    ?>
<option data-name="<?php echo $chair['name']; ?>" data-phone="<?php echo $chair['phone']; ?>" data-detail="<?php echo $chair['detail']; ?>" value="<?php echo $chair['chair_no'];?>"><?php echo $i ?></option>
<?php
    }
?>
</select>

Jqery:

function update( elem ) {
     var name = $(elem).find("option:selected").attr("data-name");
     var phone= $(elem).find("option:selected").attr("data-phone");
     var detail = $(elem).find("option:selected").attr("data-detail");
}
Comments