如何使用jQuery从查询中获取所有数据并将其放入输入框

how to get all the data from query and put it input box using jquery

本文关键字:输入 数据 jQuery 何使用 查询 获取      更新时间:2023-09-26

我想将所有数据放入输入框中,我将在选项框中选择要查看的成分的名称,例如在我的数据中ingID 有一个 1,2,3名字有土豆,胡萝卜,豆类公斤有一个 3,4,5

如果我选择了马铃薯,则输入 ingID 中的值将为 1,输入名称的值将为马铃薯,输入公斤的值将为 5

这可能吗?

<input type="text"  id="ingID" name="ID">
<input type="text"  id="name" name="name">
<input type="text"  id="kilo" name="kilo">

<?php
    include "core/database/connect.php";
    $result = mysql_query("SELECT  ingID , name , kilo FROM ingredients");
    while($row = mysql_fetch_array($result)) {
        echo '<option value = " ' .$row["name"]. ' " >'.$row["name"].'</option>';
    }                   
?>  

你可以简单地用jQuery做到这一点。我将每个选项的值属性设置为数据库中记录的 ID。但你也可以使用类似的东西 data-id .

我已经设置了一个jsfiddle:http://jsfiddle.net/8Pe9E/

.HTML:

<div>ID: <input type="text"  id="ingID" name="ID"></div>
<div>Name: <input type="text"  id="name" name="name"></div>
<div>Kilo: <input type="text"  id="kilo" name="kilo"></div>
<div>Ingredients:
<select name="ingredients">
    <option value = "1" data-kilo="3" >potato</option>
    <option value = "2" data-kilo="4" >carrot</option>
    <option value = "3" data-kilo="5" >beans</option>
</select>
</div>

和jQuery:

$('select[name="ingredients"]').change(function() {
    var opt = $(this).find('option:selected');
    $('input#ingID').val($(opt).val());
    $('input#name').val($(opt).text());
    $('input#kilo').val($(opt).data('kilo'));
});

选择字段当前是静态的,但您可以轻松更改此设置。

您也可以为此使用数据属性。

include "core/database/connect.php";
 $result = mysql_query("SELECT  ingID , name , kilo FROM ingredients");
 $select = "<select class='getData'>";
 while($row = mysql_fetch_array($result)) {
            $select .= '<option value = " ' .$row["name"]. ' "  data-kilo="'.$row["kilo"].'" data-name="'.$row["name"].'"  data-ingID="'.$row["ingID"].'">'.$row["name"].'</option>';
        }      
 $select .= "</select>";
 echo $select;

还有你的jquery代码。

$(document).ready(function(){
 $(".getData").bind('click',function(){
       var name = $(this).attr('data-name');
       var kilo = $(this).attr('data-kilo');
       var ingID = $(this).attr('data-ingID');
       $("#ingID").val(ingID);
       $("#name").val(name);
       $("#kilo").val(kilo);
 })
})