dra11767 2015-08-21 12:32
浏览 74
已采纳

如何使用JavaScript或jQuery选择文本并在另一个文本字段中显示它

I have a PHP/AJAX search script working just fine. The problem is when I type something in the text field the suggestions appear below, but they cannot be selected. In short, I want to select one of the suggestion and show the value in the search text field upon selecting it.

I have tried a solution in JavaScript, but it doesn't work. It shows an error in the console like "the select value is null".

ajax.php

<head>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

</head>
<body>
<input id="sear" autocomplete="off" type="text" name="search" 
placeholder="Seaarch here" onkeyup="search(this.value)">
<div onclick="ali()" id="list" ></div>

<script>
function search(str){
if(str.length ==0){
    document.getElementById("list").innerHTML="Please Enter Something";
    return;}
xml=new XMLHttpRequest();
xml.onreadystatechange=function(){
    if(xml.readyState==4 && xml.status==200){
        document.getElementById("list").innerHTML=xml.responseText;}
    }

xml.open("GET","search.php?char="+str,true);
xml.send();
}
</script>
<script>
document.addEventListener("DOMContentLoaded",function(){
function ali(){
var acs;
var x=document.getElementById("#list").select();
acs=x.value;
document.getElementById("#sear").innerHtml=acs;
}
});
</script>
</body>

search.php

    <?php
$con=mysqli_connect("localhost","root","","userdiary");
$str=$_GET['char'];

$sql="SELECT * FROM `login` WHERE `user_id` LIKE '$str%' OR `user_name` LIKE 
'$str%'";
$query=mysqli_query($con,$sql);
if(mysqli_num_rows($query)>0){
while($res=mysqli_fetch_assoc($query)){
echo "<option>" .$res['user_name']."</option>"."<hr>";
}
}
else{
echo "No match Found..";
}
?>
  • 写回答

3条回答 默认 最新

  • dougaimian1143 2015-08-21 13:02
    关注

    If the #sear element looks something like this once suggestions populate into it:

    <div id="list">
        <option>test</option>
        <option>test a</option>
        <option>test b</option>
    </div>
    

    then you can try this for your jQuery script:

    $('#list option').on('click', function() {
        $('#sear').val($(this).text());
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

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