I have a search box that gives you a list of suggested results based on data from a MySql database. If the user types A and the words Apple
and Animal
are in the databse, then the suggestion box will show both results. Currently, there is no way for me to click one of the results and have it fill the text box, and no matter what I try and do, I can't seem to get it to work. Currently, I'm working with something that looks like this:
echo '<script type ="text/javascript">';
echo 'function textFill(){';
echo ' var txt=document.getElementById("userInput").value= <li onclick ="textFill(this.value)">' .$matched[$count].'</li>'; //Suggestion results
echo '}';
echo"</script>";
}
I'll be honest, I'm not sure if this is even the right path to be going, but I found a few examples that were vaguely similar to this, so that's that direction I went with it. With this set up, the suggestion box doesn't even display, but if I take away the echo '<script type ='text/javascript>'
it will display the results plus the whole line of getElement
code. How would I go about getting this to work properly? I can show more code if necessary.
EDIT: I'm providing more code to show more of my PHP:
if(isset($_GET['userInput'])){
$value = $_GET['userInput']; //assign the value
strtolower($value);
}else{
echo "no input";
}
//Select query
$sql = "SELECT Device_type FROM Device WHERE Device_type LIKE '%".$value."%';";
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
//Store the result in an array list[]
while($row = mysqli_fetch_array($result)){
$list[] = $row['Device_type'];
}
}else{
//set a null value to list[] if no result to prevent error
$list[] = "";
}
}
if(!empty($value)){
if($matched = preg_grep('~'.$value.'~i', $list)){
$count = 0;
echo '<ul>';
while($count < sizeOf($list)){
if(isset($matched[$count])){
echo '<li > ' .$matched[$count].'</li>';
}
$count++;
}
echo '</ul>';
echo json_encode($data);
}else{
echo "No result";
}