Why on paste it saves on second input?

jquery

#1

Hello everyone!

I have 3 inputs and on paste on first 2 i want to add value and focus on next input. Instead on paste it focus on next input and paste in it leaving first input empty :frowning:

here is fiddle: http://jsfiddle.net/master1991/xae35coq/3/

Code:

<input id="aa">
<input id="bb">
<input id="cc">

$("#aa").on("paste",function(e){
    	$("#bb").focus();
});
$("#bb").on("paste",function(e){
    	$("#cc").focus();
});

Try to past some random text on first input! it will jump and fill next input :frowning:
How to fix this?


#2

paste fires before the insert happens and it inserts into the focused element. so if you change the focus beforehand, you change the target location for the insert.


#3

@Dormilich

i just figured this solution:

$("#aa").on("paste",function(e){
	if (this.value.length>0){
    	$("#bb").focus();
	}
});
$("#bb").on("paste",function(e){
	if (this.value.length>0){
    	$("#cc").focus();
	}
});

Is it correct?


#4

wouldn’t it make more sense to hook into the change event then?


#5

@Dormilich it works with barcode scanner so on paste is better as much as i know


#6

i need user to be able to enter code with hand and scanner and paste works for this! Just need it to past on focused input


#7

Change fires if someone types into the field, rather than only if they paste.

You COULD do it by inspecting the event, preventing the default, and doing the paste yourself.
(spitballing, untested)

$("#bb").on("paste", function (e) {
        e.preventDefault(); 
        var pasted = e.originalEvent.clipboardData.getData('text');
        $(this).val($(this).val()+pasted);
        $("#cc").focus();
}

Note that this does not allow for pasting in-place, only appending at the end.

EDIT: Except it’s an input tag, so .val instead of .html. Derp.


#8

@m_hutley This does it really nice :slight_smile: Thanks allot!