douchi5822 2015-07-09 03:18
浏览 187

从数据库填充Datalist

am new to javascript and php however i want to populate a datalist from mysql table but have some difficulties the relevant codes are presented below.I am able to fetch data from the database but not able to display them in the datalist element.

the HTML code

<form class="form" action="insert.php" method="post" name="access_form">

<ul>

<li>
<h2>Please Fill The Form</h2>

</li>

<li>
     <label for="firstname">First Name</label>
      <input name="firstname" id="keyword" type="text" placeholder="type first name (required)" required />
      <datalist id="results">
    
</datalist>
</li>

this is the javascript code

var MIN_LENGTH = 1;

$( document ).ready(function() {
    $("#keyword").keyup(function() {
        var keyword = $("#keyword").val();
        if (keyword.length >= MIN_LENGTH) {
            $.get( "auto-complete.php", { keyword: keyword } )
            .done(function( data ) {
                $('#results').html('');
                var results = jQuery.parseJSON(data);
                $(results).each(function(key, value) {
                    $("datalist").empty();
                                        $("datalist").html(data);
                })

                $('.item').click(function() {
                    var text = $(this).html();
                    $('#keyword').val(text);
                })

            });
        } else {
            $('#results').html('');
        }
    });

    $("#keyword").blur(function(){
            $("#results").fadeOut(500);
        })
        .focus(function() {     
            $("#results").show();
        });

});

the php code is below

  <?php
  require('constant.php');
   require('database.php');

  if (!isset($_GET['keyword'])) {
      die();
    }

  $keyword = $_GET['keyword'];
  $data = searchForKeyword($keyword);
  echo json_encode($data);
  ?>

please any suggestions

</div>
  • 写回答

1条回答 默认 最新

  • dqsk4643 2015-07-09 04:00
    关注

    It looks like your $.each is going to empty the dataset for every result.

    Try this instead.

    $("datalist").empty();
    $(results).each(function(key, value) {
       $("datalist").append($("<option>").innerHTML(data));
        })
    

    You'll be creating a new option element and appending it to the datalist element.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器