aristeidhsP aristeidhsP - 1 year ago 71
Javascript Question

Select first search item without clicking to it in Jquery

Hello I have a html file that has several inputs which are autofilled when a matching item is selected on auto-complete

My html file is:

<table class="table table-bordered">
<input class="form-control" type='text' id='barcodescanr' name='barcodescanr' />
<li><label>Surname </label>
<input class="form-control" type='text' id='surname_1' name='surname' required/>
<input class="form-control" type='text' id='name_1' name='name' required/>
<li><label>Company Name</label>
<input class="form-control" type='text' id='company_name_1' name='company_name' required/>

My search looks like this

The autocomplete that fills the input fields is this and it works through barcode scanning

source: function( request, response ) {
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'barcodescanr',
row_num : 1
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
autoFocus: true,
minLength: 3,
select: function( event, ui ) {
var names ="|");
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );

How could I select the first matching barcode from auto-complete without clicking on that? Thank you

Answer Source

try this

     $('#ui-id-1 li:first-child').trigger('click');

or this, when user stop writing

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 2000;  //time in ms, 5 second for example
var $input = $('#barcodescanr');

//on keyup, start the countdown
$input.on('keyup', function () {
  typingTimer = setTimeout(doneTyping, doneTypingInterval);

//on keydown, clear the countdown
$input.on('keydown', function () {

//user is "finished typing," do something
function doneTyping () {
  $('#ui-id-1 li:first-child').trigger('click');

Play with the value of doneTypingInterval to your liking.