当select的值为ID时,从mysql获取数据到输入标签

时间:2016-09-23 08:49:04

标签: javascript php html

我有MySQL表"名称":

  id |    name   |   country  |    age  
  1  |    Mark   |   Germany  |     20  
  2  |    Jack   |    UK      |     23  
  3  |    Mary   |    US      |     32  
  4  |   Suzan   |   Italy    |     15  

我需要的是:

  • 当我选择2时,我希望输入标签的设定值为23
  • 当我选择4时,我希望输入标签的设定值为15
<html>
    <body>
        <select  id="name" name="name"  required  >
            <option></option>
            <option  value="<?php echo $row['id'];?>" >
                <?php echo $row['name']; ?> - <? echo $row['country']; ?> - <? echo $row['age']; ?>  
            </option> 
        </select>
        <input type="number"  id="age" name="age" value=" " placeholder=" age" required>
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

你需要做两件事:

首先,将要用作值的值放在选项的值中。

为了简化示例,请参阅HTML,该选项的值是您需要的值!所以没有理由设置一个ID并获得年龄..即使有可能,也没有理由这样做..

&#13;
&#13;
var mySelect = document.getElementById("name");
mySelect.addEventListener("change", myFunction);

function myFunction()  {
	document.getElementById("age").value = mySelect.options[mySelect.selectedIndex].value;
};
&#13;
<select  id="name" name="name"  required  >
    <option  value="1" >
        name1 - country1 - age 1
    </option>
    <option  value="2" >
        name2 - country2 - age 2
    </option>
    <option  value="3" >
        name3 - country3 - age 3
    </option>
    <option  value="4" >
        name4 - country4 - age 4
    </option>
</select>
<input type="number"  id="age" name="age" value="" placeholder=" age" required>
&#13;
&#13;
&#13;

然后,第二:要获得上面的HTML,你可能需要在PHP中编写类似的东西

<select  id="name" name="name"  required  >

    <?php
        // assuming you get your MySQL results in a array called $rows
        foreach($rows as $row) {
            echo '<option  value="'.$row['age'].'">'.
                     $row['name'] . ' - ' . $row['country'] . ' - ' . $row['age']
            .'</option>';
        }
    ?>

</select>
<input type="number"  id="age" name="age" value="" placeholder=" age" required>