Why on paste it saves on second input?

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?

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.

@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?

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

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

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

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.

1 Like

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

You might account for this by checking the element’s .selectionStart / .selectionEnd and split its .value accordingly… but another solution would be to schedule the .focus() to the next tick, so that the default action can take place as usual:

$("#aa").on("paste",function (){
  window.setTimeout(function () {
    $("#bb").focus()
  })
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.