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条)

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器