简体   繁体   中英

Changing focus from one input to the next with a barcode scanner

I am using a barcode scanner to enter data into input fields on a webpage. I set up the form and autofocus on the first input field. When the first barcode is entered into the first input field I would like focus to jump to the next input field. However, as soon as I enter the first barcode the form 'submits'. Here is the html I am using:

    <form id="barcode1" name="barcode" method="Post" action="#">

       <div>
          <label for="S1">Barcode 1 </label>
          <input id="S1" class="bcode" type="text" name="S1" autofocus/> 
          <label for="S2">Barcode 2 </label>
          <input id="S2" class="bcode" type="text" name="S2" />      
          <label for="S3">Barcode 3 </label>
          <input id="S3" class="bcode" type="text" name="S3" />
       </div>
       <p><input type="submit" name="Submit" value="Submit"></p>

    </form>

I have tried solutions from similar SO questions here and [here] ( http://jsfiddle.net/davidThomas/ZmAEG/ ), but they don't seem to work.

Ideally I would like to have a solution something like this (the second link above), so please let me know where or why this is not working and what I can do to fix it.

    $('form').on('keypress','input',function(e){
        var eClassName = this.className,
            index = $(this).index('.' + eClassName) + 1;
        if (e.which === 13){
            e.preventDefault();
            $('input.' + eClassName)
                .eq(index)
                .focus();
        }
    });

If your barcode scanner is a keyboard wedge, you should be able to configure the trailing character to a TAB.

It seems like, by default, your scanner is trailing with an ENTER (carriage return).

Another option would be to also check for a LF (decimal 10) in your javascript code.

You need to return false in order to prevent the enter key from submitting the form.

The answer to this question will help you: Prevent form submission with enter key

//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
    if ( e.which == 13 ) // Enter key = keycode 13
    {
        $(this).next().focus();  //Use whatever selector necessary to focus the 'next' input
        return false;
    }
});

No need to make any changes to your bar scanner.

Looks like your function will never get called because browser submits the form on Enter . You may have to suppress submit until all fields are filled (or some other condition) by intercepting submit event first.

$( "form" ).submit(function( event ) {
  if(/*all req. fields are filled -> submit the form*/)
     $(this).submit();
  event.preventDefault();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM