JCD February 2016

Jquery - Break up values into individual input fields

The following app copy's excel values and breaks them up into individual input fields.

Everything works great but i'm loosing the first value.

For example, if i create 5 entries. The first input field's id is 001, second is 002 etc etc.

When i copy and paste an excel column, the value for 002 gets copied to the 001 id.

Here's the data I'm copying from Excel

1 2 3 4 5

!http://imgur.com/nxe6yDq

https://jsfiddle.net/jdarville/r9tp7762/1/

$( document ).ready(function() {
    $("#uncinfo").bind("paste", function(e){
        // access the clipboard using the api
        var pastedData = e.originalEvent.clipboardData.getData('text');
        arr = pastedData.split(/\s+/);
        for(i=1; i < arr.length; i++){
            $("#unc"+i).val(arr[i]);
        }
    } );
});

Answers


SoluableNonagon February 2016

Try changing i to 0

    for(var i=0; i < arr.length; i++){
        $("#unc"+i).val(arr[i]);
    }


bohuss February 2016

this happens because your arrays are 0 based, while your inputs are 1 based, for example for usernames you should use:

for(i=0; i < arr.length; i++){
    $("#user"+(i+1)).val(arr[i]);
}

test this approach here:

https://jsfiddle.net/1jpL4L2n/1/

another solution would be to move the id incrementing after creating the table rows:

$("#table").append('<tr>...</tr>');
x++; //text box increment

this way you will have your input ids 0 based: #unc0, unc1, ... in this case your loop for filling would be:

for(i=0; i < arr.length; i++){
    $("#user"+i).val(arr[i]);
}

you can test this approach here:

https://jsfiddle.net/h50h35vj/2/


Mohammed Raja February 2016

$("#uncinfo").bind("paste", function(e){
				// access the clipboard using the api
				var pastedData = e.originalEvent.clipboardData.getData('text');
				arr = pastedData.split(/\s+/);
				for(i=1; i <= arr.length; i++){
					$("#unc"+i).val(arr[i -1]);
				}
			});

Check this

Post Status

Asked in February 2016
Viewed 2,132 times
Voted 8
Answered 3 times

Search




Leave an answer