0

I have been trying to create a rough autocomplete input box and am almost there. However, getting stuck at a certain point. Do check the code before i identify the problem.

JS

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
function getres(){
var x = document.getElementById("cit");
$('#resdiv').fadeIn('fast').load('results.php?cit='+x.value);
}
</script>

<script type="text/javascript">
$(document).ready(function(){
$("#resdiv a").click(function(){
    var value = $(this).html();
    var input = $('#cit');
    input.val(value);
        $('#resdiv').fadeOut('fast'); 
});
});
</script>

Some CSS

<style>
a{text-decoration:none}
a:link{color:#446666;}
a:hover{background-color:blue;padding:5px;margin:10px;color:white}
</style>

HTML

<input type="text" name="" id="cit" onkeyup="getres()">

<div id="resdiv">
<a href="#" class="test">Test 1</a>
<a href="#" class="test">Test 2</a>
<a href="#" class="test">Test 3</a>
</div>

PHP (results.php)

 <?php
if(isset($_GET['cit'])){$cit= $_GET['cit'];}
include('connnew.php');
$getprops=$clientdb->query("SELECT * FROM cities WHERE city LIKE '%$cit%'")  or die ($clientdb->error);
while($info=$getprops->fetch_assoc()){

       echo "<a href='#' class='test'>$info[city]</a><br>";

    //echo "<a href='#' style='text-decoration:none;'>$info[city]</a><br>";
}
?>

My problem is, though everything works, when I click on the hrefs Tes1, Test2 and Test3, the input box #cit gets filled with the value, but not the values of href populated by the PHP into the same #resdiv !

Why is it so ? WIll the click function of jquery work only on hrefs written as text ? And not on the populated hrefs ?

user3526204
  • 509
  • 5
  • 22
  • i see you arent using jquery's autocomplete functionality? https://jqueryui.com/autocomplete/ – Fallenreaper Jul 15 '16 at 18:41
  • I am not really familiar with it and have been trying to create my on quick fix :) – user3526204 Jul 15 '16 at 18:43
  • 2
    You need to use a delegated event handler as you use `load()` (and hence an AJAX request) to add the additional `a` elements from your PHP page *after* the DOM has loaded. See the question I marked as duplicate for the solution – Rory McCrossan Jul 15 '16 at 18:43
  • Thanks a ton. I believe even this is an answer ! As I wasn't aware of the other solution. Referring to the solution you pointed solved my issue ! Thanks again. – user3526204 Jul 15 '16 at 19:09
  • 1
    @user3526204 i hope people pay attention to your comment. I am also victim of same thing. It's not stack fault, it's the dumb peoples who down-voting without any reason. – Alive to die - Anant Jul 15 '16 at 21:14

0 Answers0