I have this ajax autocomplete function that works on every input field with a class of .train. However, the suggestions that are being passed into the .suggest_q class are being displayed in every .suggest_q, next to each .train input field, and not just the .train field that is being used. I believe I am using the correct selectors as I am using ‘this’ instead of .train near the .click function but I am still having issues. I want this function to only work on the .suggest_q and .train classes that are being used by the user and to have the other ones not display any suggestions. What would be the best way to have the autocomplete function to work with the .train and .suggest_a that is being typed in?
here is my ajax code for adding new .train input fields:
<script type="text/javascript">
$(function() {
var scntDiv = $('#p_scents');
var i = $('#p_scents p').size() + 0;
$('#addScnt').live('click', function() {
$('<p><input type="text" name="train[]" autocomplete="off" class="train" /><span class="suggest_q" id="suggest_q"></span><a href="#" id="remScnt">Remove train</a></p>').appendTo(scntDiv);
i++;
return false;
});
$('#remScnt').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
here is the ajax autocomplete code
<script type="text/javascript">
$(document).ready(function() {
$(".train").each(function(index, element) {
$(".train").live("keyup", function() {
$(".suggest_q").html("");
var train = $(this).val();
train = $.trim(train);
if(train)
{
$.ajax({
url: "train_ajax_query.php",
data: "train="+train,
success: function(msg) {
$(".suggest_q").html(msg);
$(".suggest_q ul li").mouseover(function() {
$(".suggest_q ul li").removeClass("hover");
$(this).addClass("hover");
})
$(".suggest_q ul li").click(function() {
var value = $(this).html();
$(element).val(value);
$(".suggest_q ul li").remove();
});
}
});
}
});
});
});
</script>
here is the HTML
<div id="p_scents">
<input type="text" class="train" size="20" autocomplete="off" name="train[]" />
<div id="suggest_q" class="suggest_q">
</div>
</div>
In your autocomplete code, you use a global selector. You need to save the selected elements and then use these variables.
The code has not been tested, but should work. Leave comments if you find any error, i will edit.