I am trying to implement an autosuggest functionality in the program I am making where suggeswtions of the ingredients of the recipe shall hover down the textfield are the user would type something. But I am having problem on how to target the element using its ID. The textfields are added dynamically on the page and here is my code:
$('#button').click(function(){
var id = $('.gc').length + 1;
var n = $('.num_of_fields').val(), // number of groups to add
new_row = '<span class="gc group" id="'+id+'">'
+'<input type="text" name="ingr_name[]" id="input_' +id+'" onkeyup = "suggest(this.value)" onblur = "fill()" value="" autocomplete="off" /> '
+'<?php echo form_input('amount[]', set_value('amount[]')); ?> '
+'<?php echo form_input('unit[]', set_value('unit[]')); ?> '
+'<span class="remove">Remove</span>'
+'<div class="suggestion_box" id="suggestions_' +id+'" style="display: none;">'
+'<div class="suggestion_list" id="suggestion_list_' +id+'"> </div>'
+'</div>'
+'</span>';
for ( var i = 0; i < n ; i++ ) {
$("#ingr").append(new_row);
}
return false;
});
Now, I could successfully add fields on the fly and I’m stuck on how to make the autosuggest work. I am trying with this code:
function suggest(input_string)
{
var id = $(this).attr('id');
if(input_string.length == 0)
{
$('#suggestions').fadeOut();
}
else
{
//$('#input').addClass('load');
$.post("<?php echo base_url(); ?>recipe/autosuggest", {query_string: ""+input_string+""}, function(data) {
if(data.length > 0)
{
$("#suggestions").fadeIn();
$("#suggestion_list").html(data);
//$("#input").removeClass('load');
}
});
}
}
function fill(this_value)
{
$(".input").val(this_value);
setTimeout("$('#suggestions').fadeOut();", 100);
}
I have tried to see if my var id = $(this).attr(‘id’); would give the the ID of the input field but unfortunately, it doesn’t give me what I need.
Is there a way for me to solve this? Your help will be highly appreciated. Thanks a lot.
By the way, to be exact, I wanted to get the id of ” so that I could just simply do like:
("#suggestions_" +id).fadeIn();
("#suggestion_list_" +id).html(data);
In your suggest function, it has no idea what
thisis. You can change your suggest function to be like the following:and then call that function like this:
instead of:
Hope this helps.