duancheng3342 2012-02-16 18:08
浏览 23
已采纳

使用PHP数组数据创建和操作HTML表单

I am having a bit of trouble writing a piece of code and trying to get it to work the way I want it work.

I have this array which is off my database

Array ( [0] => Array ( [id] => 1 [title] => Test 1 [comment] => Test 1 ) [1] => Array ( [id] => 2 [title] => Test 2 [comment] => This is the second test!! ) ) 

each row of data has an id, title and comment.

I have this dropdown menu

<select name="Selection" id="Selection">
    <?php
      echo "<option selected='selected' value='Default'>Please Make a Selection</option>";
         foreach($array as $row){
            echo "<option>" . htmlentities($row['title']) . "</option>";
         }

    ?>
</select>

I am trying to get it so that when the user selects a title, the comment associated with that title goes into the comment text box below.

<p id="commentContainer">
<label for="comment">Comment</label>
<textarea name='comment' id='comment' cols="40" rows="5"><? echo htmlentities($array["comment"]); ?></textarea>
</p>

And I also have this Javascript

<script type="text/javascript">

$(document).ready(function() {
    $('#selection').change(function(){
        var commentId = $(this).val();
        $('#comment').val(commentId);
    })
});

</script>

This gets the value of the what is selected in the dropdown to the comment textbox.

How would I get the comment assoicated with the title in the comment textbox? Would I have to set the value of the dropdown selections as the ids? This is where I am stuck and I have been googling my heart out for an answer.

  • 写回答

5条回答 默认 最新

  • dongpu8935 2012-02-16 18:37
    关注

    Seems like JavaScript is a must-have for this solution. See if you can get this approach to work:

    Step 1: json_encode() your array data so that it can be used inside JavaScript. Suppose it ends up looking something like this:

    var selectionData = {
        "1": {
            "title": "Test 1",
            "comment": "Comment 1"
        },
        "2": {
            "title": "Test 2",
            "comment": "Comment 2"
        }
    };
    

    Step 2: Use this object to populate the select:

    $.each(selectionData, function(id, data) {
        $("<option/>").attr({
            "value": id
        }).text(data.title).appendTo("#Selection");
    });
    

    Step 3: Use this object to update the comment box:

    $("#Selection").change(function() {
        var id = $(this).val();
        $('#comment').val(selectionData[id].comment);
    });
    

    Demo here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?