简体   繁体   中英

Change focus to next input field on "Enter" key with VueJS & Quasar

I have a form that works strictly with a Barcode code that simulates an Enter event at the end of the read. (No keyboard and mouse). I'm having a hard time sending the focus to the next element (input sometimes a button). I prepared a playground for you so you can checkout my code. At some point this worked before a quasar dress-up and now it isn't. I refuse to think this is a quasar issue and more like a "I suck" problem lol.

The process is simple in theory. Wait for the input field to read the entire barcode before it fires the focus event. My best guess is to use the change event. When I tried the input or keydown event, it registered other stuff and fired other functions on every digit.. Big no-no, especially when making api calls.

Here is my sendFocus method.

sendFocus: function(e) {
    document.addEventListener("keydown", function(e) {
        var input = e.target.nodeName.toLowerCase() === "input";
        var form = e.target.form;
        if (e.key === "Enter" && input) {
            var index = Array.prototype.indexOf.call(form, e.target);
            form.elements[index + 1].focus();
        }
    });
}

And the link to the codepen . Thanks in advance

With @change (or native DOM onchange ) event, any associated handler will get invoked as many times as you hit a key on the keyboard, and in your case, you are literally attaching a new handler every time a key is pressed (you seem to be good with Javascript and jQuery, so I hope the codepen was just for mere illustration... Unless I'm missing something?).

But anyway, in Vue (for this particular purpose), we usually want @keydown.enter . Have a read on Event Handling with Key Codes .

That being said, there are several approaches to achieving this "jump-to-next-field" behavior, but please consider the following example (which should also be applicable to Quasar's q-input ).

 new Vue({ el: '#app', methods: { focusNext(e) { const inputs = Array.from(e.target.form.querySelectorAll('input[type="text"]')); const index = inputs.indexOf(e.target); if (index < inputs.length) { inputs[index + 1].focus(); } } } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script> <div id="app"> <form> <div> <label>Field #1</label> <input type="text" @keydown.enter="focusNext" /> </div> <div> <label>Field #2</label> <input type="text" @keydown.enter="focusNext" /> </div> <div> <label>Field #3</label> <input type="text" /> </div> </form> </div>

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