jQuery Mobile:基于列表中的选择更新MySQL表的输入


jQuery Mobile: Updating an input from MySQL table based on a selection from a list

我正在编写一个jQuery移动页面(PHP),填充一个选择元素,它的选项标签与"项目"从一个MySQL数据库表(表包含id,项目,成本)。使用常用的mysql_query和mysql_fetch_assoc方法回显这些选项,效果很好。剥离为裸代码:

<?php
    $itemQuery = mysql_query("SELECT shortDesc FROM `items` ORDER BY shortDesc");
?>
<label for="item" class="select">Item:</label>
    <select name="item" id="item" data-native-menu="false">
        <option>Select Item:</option>            
        <?php
            while($temp = mysql_fetch_assoc($itemQuery))
            {
                echo "<option value='".$temp['shortDesc']."'>".$temp['shortDesc']."</option>";
            }
        ?>
    </select>

我想但是能够更新下面的输入元素,称为"成本"与实际项目的成本从MySQL表,当用户从列表中选择一个项目,我不确定如何使用jQuery/PHP/MySQL做到这一点。成本输入字段:

<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>

我也不确定我们是否可以从已经在$itemQuery中返回的结果中以某种方式获得成本值(通过将SELECT更改为shortDesc,成本)保存另一个数据库查询,或者我们是否必须再次查询数据库以执行选择,其中用户的选择= shortDesc。

我怀疑在不同的形式下,这是开发人员的共同需求;本质上是根据用户的选择/交互从数据库中抓取一些信息。我在谷歌上搜索过,但我不确定我是否使用了正确的搜索词来找到我怀疑在其他地方已经得到答案的东西!

一如既往地感谢您的帮助。

你可以这样做:

1)循环你的查询结果,写你的选项和一些javascript(我使用关联数组)

<?php
    $result = mysql_query("SELECT shortDesc,costs FROM items ORDER BY shortDesc");
    $options = '';
            $javascript = ''; 
    while ($row = mysql_fetch_assoc($result))
    {
        $options .= '<option value="'.$row['shortDesc'].'">'.$row['shortDesc'].'</option>';
        $javascript .= ''''.$row['shortDesc'].''' : '''.$row['costs'].''',';
    }
?>
2)编写你的HTML和javascript:
<select id="yourselect">
    <option>select</option>
<?=$options?>
</select>
<label for="cost">Cost:</label>
<input type="text" name="cost" id="cost" value="" placeholder="Cost (£)"/>

3)写一些javascript来更新你的输入字段:

<script>
    var costs = {<?=$javascript?>};
    $(function() {
    $('#yourselect').change(function() {
    cost = costs[$('#yourselect').val()];
    $('#cost').val(cost);

    });
    });
</script>