php - jQuery 移动 : Updating an input from MySQL table based on a selection from a list

标签 php jquery mysql jquery-mobile

我正在编写一个 jQuery 移动页面(使用 PHP),该页面使用 MySQL 数据库中的表(该表包含 id、items、cost)中的“items”填充 select 元素及其选项标记。使用常用的 mysql_query 和 while 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 表中的实际项目成本来更新名为“cost”的输入元素,但我不确定该怎么做使用 jQuery/PHP/MySQL。成本输入字段:

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

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

我怀疑以不同的形式,这是开发者的共同需求;本质上是根据用户的选择/交互从数据库中获取一些信息。我已经在 Google 上查看并在这里进行了搜索,但我不确定我是否使用了正确的搜索词来查找我怀疑在其他地方已经得到解答的内容!

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

最佳答案

你可以这样做:

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>

关于php - jQuery 移动 : Updating an input from MySQL table based on a selection from a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001492/

相关文章:

php - 如果发生数据库查询错误,CodeIgniter 3不会返回false

php - Laravel 对关系的 Eloquent 复杂查询

javascript - Bootstrap Studio 中特定于页面的脚本

php - 在哪里保存数据?

php - MySQL/PHP/JS 动态填充下拉菜单

php - 如何回应查询

php - 数据库架构 - 创建一个大表还是多个?

javascript - 为什么 "_=1389258551926"在 ajax 请求中作为查询字符串参数发送?

php - 多个jquery-ui id应用于从数据库返回的值

java - 为什么数据库中的所有数据都没有显示到我的 JTextfield 上