Need Help with selecting a list element from ul. List elements are built dynamically from database reads.

Need Help with selecting a list element from ul. List elements are built dynamically from database reads.

Need Help with selecting a list element from ul. List elements are built dynamically from database reads.

Here is the code snippet.

Part 1. Basically reads the database from a server and post matching suggestions. Which is working absolutely fine.

var scopeName = debounce ( function( arg) {

var value = arg. trim();
var scope = $( "#scope"). val();
var cc = $( "#find"). attr( "class");

$. get ( "/q/" +scope + "?q=" +value, function( data){

if( value.length > 0 && cc == "hideme" && (data[ 0] != undefined || data[ 0] != null)) {
$( "#find"). toggleClass( "hideme showme");
$( "#find"). empty();
data. forEach( function( ele) {
$( "#find"). append( '<li class="sconame">' +ele.taluka + '</li>');

});

} else if ( value.length > 0 && cc == "showme" && (data[ 0] != undefined || data[ 0] != null)) {

$( "#find"). empty();
data. forEach( function( ele) {
$( "#find"). append( '<li class="sconame">' +ele.taluka + '</li>');

})
} else if ( value.length > 0 && cc == "showme" && (data[ 0] == undefined || data[ 0] == null)) {
$( "#find"). empty();
$( "#find"). append( '<li class="sconame">No matching item found</li>');
} else if ( value.length < 1 && cc == "showme"){
$( "#find"). empty();
$( "#find"). toggleClass( "showme hideme");

}

});

});

function debounce( func, wait, immediate) {

var timeout;
return function(){
var context = this,
args = arguments;
var later = function () {
timeout = null;
if( !immediate) func. apply(context, args);
};

var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if(callNow) func. apply(context, args);
}
}


Part 2: Deals with selecting the elements and appending to a textarea on
enter .

$listItems = $( ".sconame"); <-- Not able to populate this as

$( "#myscope"). keydown( function( event){

var scope = $( this). val(),
key = event.keyCode,
$selected = $listItems. filter( '.selected'),
$current;


if(event.which === 13 && scope != "") {
$( this). val( "");
$( "#scopelist"). append(scope + ", ");
}

if ( key !== 40 && key !== 38 ) return;

$listItems. removeClass( 'selected');

if ( key === 40 ) // Down key
{
if ( ! $selected.length || $selected. is( ':last-child') ) {
$current = $listItems. eq( 0);
}
else {
$current = $selected. next();
}
}
else if ( key === 38 ) // Up key
{
if ( ! $selected.length || $selected. is( ':first-child') ) {
$current = $listItems. last();
}
else {
$current = $selected. prev();
}
}

$( this). val( $current. addClass( 'selected'). text() );

});