Adding the ability to insert Excel data into a Django form

Currently, I have a Django form that has N rows of 12 columns in the form of text fields in the form of a table. Users can fill out this form with one text box at a time:

[________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________ ] [________] [________] [________] [________] [________] [________] [________] [________] [________] [________]

Note. Only 9 columns are shown in this table, but the actual form I use is 12.

I would like to add the ability for users to copy a range of cells in Excel and paste into the form, filling in the corresponding cells.

I tried to imitate the syntax for a method that I successfully created that can clear all data fields after clicking the clear button on the form:

$(document).on("click", "#clear_button", function() { $("input[type=text]").val(""); }); 

The data coming from Excel for a single row is limited to tabs, and this is roughly the way I got it:

 $(document).on("paste", "input[type=text]", function(){ var input_id = $(this).attr("id"); var value = $(this).val(); var value_split_array = value.split("\t"); var row_selected = input_id.match(/([-\w]+)_\d+/)[1]; var num = parseInt(input_id.match(/[-\w]+_(\d+)/)[1], 10); for (i=num; i < value_split_array.length-1 || i < 12; i++) { $("[id="+row_selected+"_"+i+"]").val(value_split_array[i-num]); } }); 

I thought this would work, but unfortunately this did not happen. I wonder if anyone has any suggestions.

+2
source share
1 answer

The insert event is fired before the data is inserted into the input field, so you cannot get the inserted text using $(this).val() . You need to access the clipboardData property of the event object.

Since jQuery does not include clipboardData in its event object, you need to get it from the originalEvent field.

Your event handler will look like this.

 function (event) { var input_id = $(this).attr("id"); var value; if (event.originalEvent.clipboardData) { // Firefox, Chrome, etc. value = event.originalEvent.clipboardData.getData('text/plain'); } else if (window.clipboardData) { // IE value = window.clipboardData.getData("Text") } else { // clipboard is not available in this browser return; } /* ... */ event.preventDefault(); // prevent the original paste } 

To be more reliable, you should request a clipboardData file to make sure it has a text / equal representation before proceeding.

In IE, it looks like this , so you read the clipboard.

 var value = window.clipboardData.getData("Text"); 
+4
source

Source: https://habr.com/ru/post/1210240/


All Articles