Read a CSV file with javascript - javascript

I am trying to upload a CSV file to my database with php. I have problems with the numbers so I try to import the file in an array with javascript. I notice that the numbers of the CSV are different when I import it. For example the number 23447 is "23 447"(including the space and quotes). How can my code edit the form of the number?
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split(",");
if (cells.length > 1) {
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
});
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>

Just delete the spaces (whitespace characters are matched with the regex special character \s) then cast to a number. Apply this function to each csv cell value to process them:
const processNumber = str => {
const strWithoutSpaces = str.replace(/\s*/g, '');
const numberFromStr = +strWithoutSpaces;
return numberFromStr;
}
console.log(['10 000', '3 000 000', '100'].map(processNumber))

Related

How to add conditionals to user input in App Scripts with while loops?

I made a selectBox which had its range of values from a Google Sheet Column. I also want to take an Integer input value from the user and then write this value in a specific cell according to option taken from selectBox. The html link does not show the integer response box. Is it possible to do the above plan in a while loop? Would appreciate any ideas and correction of code
function doGet() {
var ap = SpreadsheetApp.openByUrl("Gsheet URL here");
var ui = SpreadsheetApp.getUi();
var user = ui.prompt("Put down a number");
var result = result.getSelectedButton();
var sheet = ap.getSheetByName("lv");
var values = sheet.getRange("A2:A10").getValues();
var options = values.map(function(row)
{
#To show show the selected option??
var item = options.getSelecteditem();
if (item === A3)
{
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
var a1 = cell.getA3Notation();
var val = cell.getValue();
SpreadsheetApp.getUi().alert("Ur value is "+a1+" value is "+val);
}
{
return '<option value="' + row[0] + '">' + row[0] + '</option>';
});
var html = '<form onSubmit="handleSubmit(this)"> Type of Cuisine' + options.join('') + '</select></form>';
return HtmlService.createHtmlOutput(html);
}
Using an Html Dialog to Control User Inputs
Not sure what you wanted so here's a complete example I whipped up for you.
Code.gs:
function processInput(obj) {
Logger.log(JSON.stringify(obj));
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [min,max,locs] = sh.getRange('B1:B3').getValues().flat();
Logger.log('min: %s max: %s locs: %s',min,max,locs)
const lA = locs.split(',');
if(obj.int > max) {
obj.msg = "Too High Try Again";
return obj;
} else if (obj.int < min) {
obj.msg = "To Low Try Again";
return obj;
} else if (!~lA.indexOf(obj.loc)) {
obj.msg = "Invalid Location";
return obj;
} else {
sh.getRange(obj.loc).setValue(obj.int);
obj.msg = "Complete";
return obj;
}
}
Following function Launches the dialog:
function launchInputDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'),"Enter Input");
}
html:
<!DOCTYPE html>
<html>
<head>
</head>
<style>input {margin: 2px 5px 2px 0;}</style>
<body>
<form>
<input type="text" id="in1" placeholder="Enter an integer" />
<br /><input type="text" id="in2" placeholder="Enter a location" />
<br /><input type="button" value="Process" onClick="processinput();" />
</form>
<div id="msg"></div>
<script>
function processinput() {
document.getElementById("msg").innerHTML = '';
let v1 = parseInt(document.getElementById('in1').value);
let v2 = document.getElementById('in2').value;
let obj = {int:v1,loc:v2,msg:''};
google.script.run
.withSuccessHandler(robj => {
console.log(JSON.stringify(robj))
if(robj.msg == "Complete") {
document.getElementById("msg").innerHTML = `Value: ${robj.int} Location: ${robj.loc} Try Again`;
document.getElementById("in1").value = '';
document.getElementById("in2").value = '';
} else {
document.getElementById("msg").innerHTML = robj.msg;
}
})
.processInput(obj);
}
</script>
</body>
</html>
Short Demo:
This version uses a <select> tag to allow the user to determine where the data will be loaded
GS:
function doPost(e) {
Logger.log(e.postData.contents);
Logger.log(e.postData.type);
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
let data = JSON.parse(e.postData.contents);
sh.getRange(data.loc).setValue(data.id)
}
function sendData(obj) {
const url = ScriptApp.getService().getUrl();
const params = { "contentType": "application/json", "payload": JSON.stringify(obj), "muteHttpExceptions": true, "method": "post", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
UrlFetchApp.fetch(url, params);
}
function displayError(msg) {
SpreadsheetApp.getUi().alert(msg);
}
function launchMyDialog() {
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('ah1'), 'My Dialog');
}
function getSelectOptions() {
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName('Options');
var rg = sh.getDataRange();
var vA = rg.getValues();
var options = [];
for (var i = 0; i < vA.length; i++) {
options.push(vA[i][0]);
}
return vA;
}
HTML:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
<input type="text" id="txt1" name="id" placeholder="Enter Numbers only"/>
<select id="sel1" name="loc"></select>
<input type="button" value="submit" onClick="processForm(this.parentNode);" />
</form>
<script>
function processForm(obj) {
console.log(obj.id.value);
if(obj.id.value.match(/[A-Za-z]/)) {
google.script.run.displayError("Invalid Characters Found in id field");
} else {
google.script.run.sendData(obj);
}
}
window.onload = function() {
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
}
function updateSelect(vA) {
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<vA.length;i++) {
select.options[i] = new Option(vA[i],vA[i]);
}
}
</script>
</body>
</html>
Demo:

Get the file extension in the JavaScript

I have a problem checking what is an extension in my multiple input files. I am added pathinfo in the javascript and alert to check the file extension, but cannot work. Below is my coding:
<!DOCTYPE html>
<html>
<body>
<input type="file" name="vasplus_multiple_files" id="vasplus_multiple_files" accept="application/msword, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*" multiple="multiple"/>
<input type="submit" name="next" class="action-button" value="Submit" onclick="sendFunc_web()"/>
<script>
function sendFunc_web(){
var inp = document.getElementById('vasplus_multiple_files');
var count = inp.files.length;
for (var i = 0; i < inp.files.length; ++i) {
var num = i+1;
var name = inp.files.item(i).name;
var ext = pathinfo(name, PATHINFO_EXTENSION);
alert("here is a file path: " + ext);
}
}
</script>
</body>
</html>
For example, if the file names are abcdefg.pdf and haha.jpeg, I want to alert twice data to show extensions are pdf and jpeg``.
The result might be like below the pictures;
Hope someone can guide me which part I am getting wrong.
Try using the following solution
function sendFunc_web() {
var inp = document.getElementById('vasplus_multiple_files');
var count = inp.files.length;
for (var i = 0; i < inp.files.length; ++i) {
var num = i + 1;
var name = inp.files.item(i).name;
var ext = name.split('.');
ext = ext[ext.length - 1];
alert("here is a file path: " + ext);
}
}
<input type="file" name="vasplus_multiple_files" id="vasplus_multiple_files" accept="application/msword, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/*" multiple="multiple" />
<input type="submit" name="next" class="action-button" value="Submit" onclick="sendFunc_web()" />
You can split the name file by dot, and access last index:
function sendFunc_web() {
var inp = document.getElementById('vasplus_multiple_files');
var count = inp.files.length;
for (var i = 0; i < inp.files.length; ++i) {
var num = i + 1;
var name = inp.files.item(i).name;
console.log(name)
let ext = ext[ext.length - 1]
console.log(ext)
}
}
RegEx (Fast & Accurate) version of pathInfo:
function pathInfo(s) {
s=s.match(/(.*?\/)?(([^/]*?)(\.[^/.]+?)?)(?:[?#].*)?$/);
return {path:s[1],file:s[2],name:s[3],ext:s[4]};
}
var sample='folder/myfolder/another/file.min.js?query=1';
var result=pathInfo(sample);
console.log(result);
/*
{
"path": "folder/myfolder/another/",
"file": "file.min.js",
"name": "file.min",
"ext": ".js"
}
*/
console.log(result.ext);

How to input a file, and then filter it and output the result into a textarea?

I have the following code that you can upload a Javascript file and it removes all comments from the document. This works perfectly. However below that I have two textareas. One is where the user pastes their code, and the same function to remove all comments is run on that code and the updated code is pasted in the other textarea. However the result comes out as undefined. What is wrong with my code. Please help me!
function fileUploaded() {
var myUploadedFile = document.getElementById("myFile").files[0];
var reader = new FileReader();
reader.readAsText(myUploadedFile, "UTF-8");
reader.onload = function(evt) {
var documentNew = evt.target.result.replace(/(\r\n|\n|\r)/gm, "\n");
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = String(filterred).replace(/;/g, "; \n");
$("#answerDocument1").html(filterred);
};
};
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
$("#doc").keyup(function(evt) {
var doc = $("doc").html();
var documentNew = String(doc).replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = String(filterred).replace(/;/g, "; \n");
$("#answerDocument2").html(documentNew);
});
textarea {
width: 100px;
height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Upload A Javascript Document</h3>
<input type="file" id="myFile">
<textarea id="answerDocument1"></textarea>
<br><br>
<hr>
<br><br>
<textarea id="doc"></textarea>
<textarea id="answerDocument2" readonly></textarea>
I have used...
filterred = filterred.join("").replace(/;/g, "; \n");
Instead of...
filterred = String(filterred).replace(/;/g, "; \n");
Because filterred is an array, and not a string, and if you convert it into a string it comes out joined by commas.
I have also used $("#doc").val(); instead of $("doc").html();, because it is the value of the <textarea></textarea> that I am getting. That makes the undefined message go away.
function fileUploaded() {
var myUploadedFile = document.getElementById("myFile").files[0];
var reader = new FileReader();
reader.readAsText(myUploadedFile, "UTF-8");
reader.onload = function(evt) {
var documentNew = evt.target.result.replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = filterred.join("").replace(/;/g, "; \n");
$("#answerDocument1").html(filterred);
};
};
document.getElementById("myFile").addEventListener("change", fileUploaded, false);
$("#doc").keyup(function(evt) {
var doc = $("#doc").val();
var documentNew = String(doc).replace(/(\r\n|\n|\r)/gm, "\n");
var str = documentNew;
var lines = str.split('\n');
var filterred = lines.filter(function(line) {
return line.indexOf('//') != 0;
});
filterred = filterred.join("").replace(/;/g, "; \n");
$("#answerDocument2").html(filterred);
});
textarea {
width: 150px;
height: 150px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Upload A Javascript Document</h3>
<input type="file" id="myFile">
<textarea id="answerDocument1"></textarea>
<br><br>
<hr>
<br><br>
<h3>Paste Code</h3>
<textarea id="doc"></textarea>
<h3>Copy Formatted Code</h3>
<textarea id="answerDocument2" readonly></textarea>

Get values from dynamic table and draws it with google charts

I'm trying to get the values from the dynamic table and after that I want draw it with Google charts, but the code doesn't work, I can't understand what's the problem. I think the problem is related to the method that I use to get the value from the table, but I'm not sure.
When I get the values and I try to draw it, Google returns the following error:
Data column(s) for axis #0 cannot be of type string
Can anyone help me to fix my code please?
Link to JSFiddle: https://jsfiddle.net/macco_cl/qaogs3sx/
var theTable, theTableBody
var myForm = document.forms.myForm;
var png = document.getElementById("png");
function init() {
theTable = (document.all) ? document.all.myTABLE :
document.getElementById("myTABLE")
theTableBody = theTable.tBodies[0]
}
function appendRow(form) {
insertTableRow(form, -1)
}
function addRow(form) {
insertTableRow(form, form.insertIndex.value)
}
function insertTableRow(form, where) {
var now = new Date()
var nowData = [now.getHours(), now.getMinutes(), now.getSeconds(),
now.getMilliseconds()]
clearBGColors()
var newCell
var newRow = theTableBody.insertRow(where)
for (var i = 0; i < nowData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = nowData[i]
newCell.style.backgroundColor = "salmon"
}
updateRowCounters(form)
}
function removeRow(form) {
theTableBody.deleteRow(form.deleteIndex.value)
updateRowCounters(form)
}
function insertTHEAD(form) {
var THEADData = ["Hours","Minutes","Seconds","Milliseconds"]
var newCell
var newTHEAD = theTable.createTHead()
newTHEAD.id = "myTHEAD"
var newRow = newTHEAD.insertRow(-1)
for (var i = 0; i < THEADData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = THEADData[i]
}
updateRowCounters(form)
form.addTHEAD.disabled = true
form.deleteTHEAD.disabled = false
}
function removeTHEAD(form) {
theTable.deleteTHead()
updateRowCounters(form)
form.addTHEAD.disabled = false
form.deleteTHEAD.disabled = true
}
function insertTFOOT(form) {
var TFOOTData = ["Hours","Minutes","Seconds","Milliseconds"]
var newCell
var newTFOOT = theTable.createTFoot()
newTFOOT.id = "myTFOOT"
var newRow = newTFOOT.insertRow(-1)
for (var i = 0; i < TFOOTData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = TFOOTData[i]
}
updateRowCounters(form)
form.addTFOOT.disabled = true
form.deleteTFOOT.disabled = false
}
function removeTFOOT(form) {
theTable.deleteTFoot()
updateRowCounters(form)
form.addTFOOT.disabled = false
form.deleteTFOOT.disabled = true
}
function insertCaption(form) {
var captionData = form.captionText.value
var newCaption = theTable.createCaption()
newCaption.innerHTML = captionData
form.addCaption.disabled = true
form.deleteCaption.disabled = false
}
function removeCaption(form) {
theTable.deleteCaption()
form.addCaption.disabled = false
form.deleteCaption.disabled = true
}
// housekeeping functions
function updateRowCounters(form) {
var sel1 = form.insertIndex
var sel2 = form.deleteIndex
sel1.options.length = 0
sel2.options.length = 0
for (var i = 0; i < theTableBody.rows.length; i++) {
sel1.options[i] = new Option(i, i)
sel2.options[i] = new Option(i, i)
}
form.removeRowBtn.disabled = (i==0)
}
function clearBGColors() {
for (var i = 0; i < theTableBody.rows.length; i++) {
for (var j = 0; j < theTableBody.rows[i].cells.length; j++) {
theTableBody.rows[i].cells[j].style.backgroundColor = ""
}
}
}
function GetCellValues() {
var table = document.getElementById("myTABLE");
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
return table;
}
function mostra() {
document.getElementById("chart_div").style.display="block";
}
function nascondi() {
document.getElementById("chart_div").style.display="none";
}
function finestra(){
if(tf == true){
window.open("pngbar.html");
//document.getElementById("chart_div").style.display="none";
}
}
function setDati(){
//if(png.checked)
// tf = true;
//else
// tf = false;
drawRightY();
}
function drawRightY() {
tf = false;
var valori = GetCellValues();
var f = new Array();
for (var i=0;i<valori.rows.length;i++) {
f[i]=new Array();
for (var j=0;j<valori.rows[i].cells.length;j++) {
f[i][j]= valori.rows[i].cells[j].innerHTML;
}
}
var data = new google.visualization.arrayToDataTable(f,true);
var options = {
chart: {
// title: z,
},
hAxis: {
minValue: 0,
},
vAxis: {
},
axes: {
y: {
0: {side: 'right'}
}
}
};
if (tf == false){
var material = new google.visualization.BarChart(document.getElementById('chart_div'));
material.draw(data, options);
}
if (tf == true) {
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
});
options = {width: 1920, height: 1080}
chart.draw(data, options);
document.getElementById("chart_div").style.display="none";
window.open(chart.getImageURI());
}
}
<HTML>
<HEAD>
<TITLE>Modifying Table Cell Content</TITLE>
<STYLE TYPE="text/css">
THEAD {background-color:lightyellow; font-weight:bold}
TFOOT {background-color:lightgreen; font-weight:bold}
#myTABLE {background-color:bisque}
</STYLE>
<SCRIPT src="funzioni.js"></SCRIPT>
<SCRIPT type="text/javascript" src="https://www.google.com/jsapi"></SCRIPT>
<SCRIPT type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawRightY());
</SCRIPT>
</HEAD>
<BODY onLoad="init(),nascondi()">
<H1>Modifying Tables</H1>
<HR>
<FORM NAME="controls">
<FIELDSET>
<LEGEND>Add/Remove Rows</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" VALUE="Append 1 Row"
onClick="appendRow(this.form)"></TD>
<TD><INPUT TYPE="button" VALUE="Insert 1 Row" onClick="addRow(this.form)"> at index:
<SELECT NAME="insertIndex">
<OPTION VALUE="0">0
</SELECT></TD>
<TD><INPUT TYPE="button" NAME="removeRowBtn" VALUE="Delete 1 Row" DISABLED
onClick="removeRow(this.form)"> at index:
<SELECT NAME="deleteIndex">
<OPTION VALUE="0">0
</SELECT></TD>
</TR>
</TABLE>
</FIELDSET>
<FIELDSET>
<LEGEND>Add/Remove THEAD and TFOOT</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" NAME="addTHEAD" VALUE="Insert THEAD"
onClick="insertTHEAD(this.form)"><BR>
<INPUT TYPE="button" NAME="deleteTHEAD" VALUE="Remove THEAD" DISABLED
onClick="removeTHEAD(this.form)">
</TD>
<TD><INPUT TYPE="button" NAME="addTFOOT" VALUE="Insert TFOOT"
onClick="insertTFOOT(this.form)"><BR>
<INPUT TYPE="button" NAME="deleteTFOOT" VALUE="Remove TFOOT" DISABLED
onClick="removeTFOOT(this.form)">
</TD>
</TR>
</TABLE>
</FIELDSET>
<FIELDSET>
<LEGEND>Add/Remove Caption</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" NAME="addCaption" VALUE="Add Caption"
onClick="insertCaption(this.form)"></TD>
<TD>Text: <INPUT TYPE="text" NAME="captionText" SIZE=40 VALUE="Sample Caption">
<TD><INPUT TYPE="button" NAME="deleteCaption" VALUE="Delete Caption" DISABLED
onClick="removeCaption(this.form)"></TD>
<TD><INPUT TYPE="button" NAME="Prendi valori" VALUE="get"
onClick="GetCellValues()"></TD>
</TR>
</TABLE>
</FIELDSET>
<!-- PNG<input type="checkbox" id="png" value="false" />-->
<input type="button" value="Draw Chart" onclick="mostra(),setDati()" />
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</FORM>
<HR>
<TABLE ID="myTABLE" CELLPADDING=10 BORDER=1>
<TBODY>
</TABLE>
</BODY>
</HTML>
You should try to narrow down your questions and post only related code.
The problem you have is you're not converting your HTML Table values from strings to numbers when you add the values from the table to your "dataArray", which causes the whole input to try to represent strings with numbers.
I modified your array building loop, and added if(i > 0) (if it's not the first row (the headings) anymore). Whole loop now looks like:
for (var i=0;i<valori.rows.length;i++) {
f[i]=new Array();
for (var j=0;j<valori.rows[i].cells.length;j++) {
if(i > 0){
f[i][j]= Number(valori.rows[i].cells[j].innerHTML);
}else{
f[i][j]= valori.rows[i].cells[j].innerHTML;
}
}
}
and it now works like a charm.
Link to jsfiddle.

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources