dongwei9365 2016-05-29 06:08
浏览 109
已采纳

如何在下拉列表中选择选项中显示数据

From my device table, I have device id, device name and image id and my drop down currently displays the the respective devices. How can I display the image id that is respective to the device selected on. I've tried messing around the code but I'm still going no where.

<select class = "form-control" id="changeDevice" name="changeDevice" >
   <option value= "  -- select a device -- " disabled selected value> -- select a device -- </option> 
        <?php
          foreach($device as $devicedrop){
          ?>
            <option value="<?php echo $devicedrop['id'] ?>">
    <?php echo $devicedrop['name'] ?> </option>
            <?php
            }
            ?>
</select>  
    <input type = "text" id="text"></input>
<script>
    $('#changeDevice').find('option:selected').text();
    var text = $(this);
    $('#text').prop(text);
</script>
  • 写回答

1条回答 默认 最新

  • duancan7914 2016-05-29 06:14
    关注

    take 'selectedIndex' property of select element. and...

    <script>
        var device = $('#changeDevice');
        var selectedIndex = device.prop('selectedIndex');
        var text = $('option', device).eq(selectedIndex).text().trim();
        $('#text').val(text);
    </script>
    

    ---- Edit

    Well. It's you again Lotse. :)

    You can store your data into DOM element (option) like...

    <?php
      $rows = ...;
      foreach($rows as $row) {
        printf('<option value="%d" data-image-id="%d" data-image-name="%s" data-device-name="%s">%s</option>', $row['id'], $row['image_id'], $row['device_name'], ...);
      }
    ?>
    

    this code generate HTML as

    <select id="#device_option">
      <option value="1" data-image-id="32" data-image-name="sample-01.jpg" data-device-name="some name">...</option>
      ...
    </select>
    

    then, now you can pick up any data from jQuery's $.data(key) function.

    <script>
      $(function() {
        $('device_option').on('change', function() {
          var options = $('option:selected', this); // take care when multiselect on
          var val = $(this).val(); // or options.val()
          var image_id = options.data('image-id');
          var image_name = options.data('image-name');
          var device_id = options.data('device-name');
          var text = options.text().trim();
    
          // you can poll data from DOM
    
        });
      });
    </script>
    

    http://www.w3schools.com/tags/att_global_data.asp

    https://api.jquery.com/selected-selector/

    https://api.jquery.com/data/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了