-1

Hi I want to simulate a user clicking on an input box. script is:

function prepareToScan(){
    $("fireRegAdd").focus();
    $('fireRegAdd').keypress();
}

and HTML is

 <h2>Add a visitor to today's fire register</h2>
 <input type="button" onmousedown="prepareToScan()" value="Add Visitor">
 <input id="fireRegAdd" name="fireRegAdd">
 </div>

I have a barcode scanner which puts the code into the input box but only when it's been "clicked". I've tried .focus() but it needs two scans to get the scan to work. The on focus is not the same as actually clicking in the box. Does any one know how to do that?

thanks

So I've found that if I add in an alert it set it correctly :

function prepareToScan(){
    alert("ready to scan");
    $("fireRegAdd").focus();
    $('fireRegAdd').keypress();


}

but I don't really want an alert box

I've added a demo of the code. When you click on the button I want there to be a blinking cursor in the input box.

function prepareToScan(){
  
 $("#fireRegAdd").focus();
 $('#fireRegAdd').click();

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div>

<h2>Add a visitor to today's fire register</h2>
<input type="button" value ="Add Visitor" onmousedown="prepareToScan()"/>
<input id="fireRegAdd" name="fireRegAdd" value="" />
</div>
user1616338
  • 557
  • 1
  • 8
  • 24

1 Answers1

0

I've discovered that it's virtually impossible to focus on an input box so that the curso blinks. I tried everything including manipulating the cursor position and using a click event.

I did however solve my problem. Barcode scanners act like keyboards. So I wrote some code which detects keyboard input. It checks for incoming keys. If it receives more than 3 in 250 ms it assumes that it is coming from the scanner. Works a treat. It'd be easy to modify to adjust for different applications. Here's the javascript code I ended up with. To make it work you need a div with id="barcode" Hope someone finds it useful.

var chars = []; 
var pressed = false; 
window.addEvent( 'keydown', function( evt ){
   //console.log(evt.key);
        chars.push(evt.key);
        setTimeout(function(){
        if (chars.length >= 3) {
            var barcode = chars.join("");
            $("barcode").value= barcode;
        }
        chars = [];
        pressed = false;
        },250);
});
user1616338
  • 557
  • 1
  • 8
  • 24