extract headers from uploaded csv file in html - javascript

I want to extract the header row of the csv files i upload and display them as checkbox options. Currently, I split based on "\n", then on "," to get the individual column names. However, it does not work for all csv files and some do not get split properly (eg, data cells are returned as column headers). Is there any functions I can use instead? Thanks! My code is shown below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js"></script>
<script type="text/javascript">
/*---CSV FUNCTION---*/
function getColumns_csv() {
var reader = new FileReader();
reader.onload = function(e){
var data = e.target.result;
var header = data.split("\n")[0] //<--- is there a better way to split columns?
header = header.split(",");
var cnt = 1;
$('#columnCheckbox').empty();
header.forEach(function(y){
$('#columnCheckbox').append('<td><input type="checkbox" name='+y+' id="columnSelect'+cnt+'" class="chkbx">'+y+'</td>');
cnt++;
});
$('.chkbx').on('click',function(){
if($('.chkbx:checked').length == $('.chkbx').length){
$('#checkall').prop('checked',true);
}else{
$('#checkall').prop('checked',false);
}
});
$('.hiddeninputs').show();
$('#submission').show();
}
reader.readAsText($('#datafile')[0].files[0]);
}
/*---//CSV FUNCTION---*/
</script>
<script type="text/javascript">
//select all button
$(document).ready(function(){
$('#checkall').on('click',function(){
if(this.checked){
$('.chkbx').each(function(){
this.checked = true;
});
}else{
$('.chkbx').each(function(){
this.checked = false;
});
}
});
});
</script>
</head>
<body>
<div>
<h3>Upload File</h3>
<!-- form to post file -->
<form method="post" enctype="multipart/form-data" id="fileform">
<input type="file" name="datafile" id="datafile">
<button type="button" class="btn btn-info" name="upload" id="upload" onclick="getColumns_csv()">Upload File</button>
<br></br>
<table class="hiddeninputs" hidden="hidden">
<tr>
<td><input type="checkbox" id="checkall">Select all</td>
</tr>
<tr id="columnCheckbox"></tr>
</table>
<br>
<input type="submit" class="btn btn-info" value="submit" id="submission">
</form>
</div>
</body>
</html>

Try with this:
var header = data.split(/[\r\n]+/)[0];
If your problem is with line splitting, this will cover more possible end of line character.

Related

how to auto detect the current form element with same class name

Iam appending a form from desktop view and adding it to mobile view (including scripts) using append() . Since Iam appending same class name and ID for form elements., on submitting form., it is identifying the mobile layout form and passing empty value on trying to get value using document.getElementsByClassName('txtbox').value.
As per my requirement., I need to give index to identify each form while appending. like document.getElementsByClassName('txtbox')[0].value. I have done an approach for same. But not getting how to increment index value on appneding. I have created plunker for same. Please let me know what I have missed.
Here is the sample code
$(document).ready(function(){
var data = $(".div1").html();
$(".div2").append(data);
$("form").submit(function(){
console.log(document.getElementsByClassName('txtbox').value);
/*console.log(document.getElementsByClassName('txtbox')[0].value);
console.log(document.getElementsByClassName('txtbox')[1].value) ; */
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="div1">
// data to be copied
<form class="search-container" onsubmit="event.preventDefault();window.open(abc/cde/+'?q='+document.getElementsByClassName('txtbox').value),'_self');">
<input type="text" class="txtbox" id="txtbox" placeholder="enter here...">
<input type="submit" name="submit" /></form>
</div>
<div class="div2">
//data to be appended
</div>
</body>
</html>
You may use $(this).find() to select .txtbox inside the form.
$("form").submit(function() {
console.log($(this).find('.txtbox').val());
return false; // for debugging
});
Also, please note that id should be unique in the documnt.
I have passed form object inside function call and used that param to identify current form.
$(document).ready(function(){
var data = $(".div1").html();
$(".div2").append(data);
});
function submitForm(form){
var txtValue = $(form).find('.txtbox').val();
console.log(txtValue);
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div class="div1">
// data to be copied
<form class="search-container" onsubmit="event.preventDefault();submitForm(this);">
<input type="text" class="txtbox" id="txtbox" placeholder="enter here...">
<input type="submit" name="submit" /></form>
</div>
<div class="div2">
//data to be appended
</div>
</body>
</html>
You can iterate through you class list like so:
var txtboxes = document.getElementsByClassName("txtbox");
for(var i = 0; i < txtboxes.length; i++){
// ... process each element here
$(txtboxes[i]).append(data);
}

Form html google scrip

Can anyone tell me how I can make the generated document pick up the data from the forms and put it as their title? I have already looked at the Google Script documentation and so far I have not found anything that can answer me or show me a similar example. Until now I have found relevant subjects and code here, but none have suited my need.
function doGet() {
return HtmlService
.createHtmlOutputFromFile('index')
}
function criarDocument(){
var doc = DocumentApp.create('Doc');
}
function criarSheet(){
var sheet = SpreadsheetApp.create('Sheet');
}
function createPresentation() {
var presentation =
Slides.Presentations.create({"title": "Presentation"});
Logger.log("Created presentation with ID: " + presentation.presentationId);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body{
background-color: lightblue;
}
</style>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<title>CRIE</title>
<script>
function criarDocument(){
google.script.run.criarDocument();
}
function criarSheet(){
google.script.run.criarSheet();
}
function createPresentation(){
google.script.run.createPresentation();
}
function titulo(){
var st = document.getElementById('student').value;
var te = document.getElementById('teacher').value;
var wo = document.getelementById('work').value;
document.getElementById('student' + 'teacher' + 'work').value;
}
</script>
</head>
<body>
<h1><p align = "center">CRIE SEU ARQUIVO</p></h1>
<div>
<form id = 'form' onsubmit="titulo">
<h2><p align = "center"> Student:</p></h2><p align = "center">
<input type="text" name="estudante" id="student">
<h2><p align = "center">Teacher: </p></h2><p align = "center">
<input type="text" name="professor" id="teacher">
<h2><p align = "center">Work Name</p></h2><p align = "center">
<input type="text" name="trabalho" id="work">
<br><br>
<button class="action" value="Submit" onclick= 'criarDocument()'>Start Document </button>
<button class="action" value="Submit" onclick='criarSheet()'>Start Sheet</button>
<button class="action" value="Submit" onclick='createPresentation()'>Start Presentation</button>
</form>
</div>
</body>
</html>
Here's a simple example of a timestamped text input into a spreadsheet from a sidebar. Don't forget to name your sheet Notes.
Code.gs
function onOpen()
{
loadSideBar();
SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();
}
function dispText(txt)
{
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sht=ss.getSheetByName('Notes');
var ts=Utilities.formatDate(new Date(), 'GMT-6', "M/dd/yyyy HH:mm:ss");
var row=[];
row.push(ts);
row.push(txt);
sht.appendRow(row);
return true;
}
function loadSideBar()
{
var userInterface=HtmlService.createHtmlOutputFromFile('sidebar');
SpreadsheetApp.getUi().showSidebar(userInterface);
}
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
$('#txt1').val('');
});
function sendText()
{
var txt=$('#txt1').val();
google.script.run
.withSuccessHandler(clearText)
.dispText(txt);
}
function clearText()
{
$('#txt1').val('');
}
console.log("My code");
</script>
</head>
<body>
<textarea id="txt1" rows="12" cols="35"></textarea><br />
<input id="btn1" type="button" value="submit" onClick="sendText();" />
</body>
</html>

Using local storage on a listbox

I am working on a history search function.
I have managed to get a working code to save the value from the textbox but I do not know how to load them into a listbox.
I want a listbox with clickable items so that I can click on a previous search value and load that value as I do from the textbox.
Here is my code:
<!doctype html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8>
<link rel="stylesheet" type="text/css" href="test.css">
<script src="jquery.js"></script>
<script src="j.js"></script>
</head>
<body>
<center>
<table>
<tr>
<td style="text-align: center">
<font size="22">Sök order</font>
</td>
</tr>
<tr>
<td>
<form action="test.php" method="post">
<input style="font-size: 44pt; text-align: center" size="9" type="text" name="txtSearch" id="txtSearch"/>
<input type="submit" id="submit" value="submit">
</form>
</td>
</tr>
</table>
</center>
</body>
</html>
And the j.js that handles the local storage function.
$(function () {
$("#submit").click(function () {
var txtSearch = $("#txtSearch").val();
localStorage.setItem('searchvalue',txtSearch);
});
});
And last my test.php that handles the post search request
<?php
$txtSearch = $_REQUEST['txtSearch'];
header('Location: '.'https://mywebsite.com/se/editor/order_info.php?webshop=23946&ordernr='.$txtSearch);
?>
How can I achieve this?
Thank you.
by js, you can
window.location = "https://mywebsite.com/se/editor/order_info.php?webshop=23946&ordernr="+localStorage.getItem('searchvalue');
to save in listbox or any other
document.getElementById("id").value=localStorage.getItem('searchvalue');
to save in array
var a = [];
a[0]=localStorage.getItem('searchvalue');

In Sinatra, how do I make a multi-page pop-under form which stays on the same page as you fill it out?

I've made a form that appears in a pop-under window, but I can't figure out how to make it multi-step.
Here's my code:
1) main.rb file:
[
'rubygems',
'sinatra',
'sequel'
].each{|g| require g}
DB = Sequel.sqlite('database.sqlite')
DB.create_table? :data_table do
primary_key :id
varchar :img_path
varchar :form1_name
varchar :form2_option
end
before do
#img_path = nil
#form1_name = nil
#form2_option = nil
end
get '/?' do
erb :index
end
post '/form2' do
user_img = params['user_img']
#img_path = './public/images/uploads/' + user_img[:filename]
File.open(#img_path,'wb'){|f| f.write(user_img[:tempfile].read)}# Copying the upload file to the server directory
#form1_name = params['form1_name'] # !!!DATAPOINT!!!
end
2) layout.erb file
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Multi-page form test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <!-- jQuery UI CSS -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- jQuery -->
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <!-- jQuery UI -->
<script src="./js/script.js"></script>
</head>
<body>
<%= yield %>
</body>
3) index.erb file
<button id="upload_form_opener" type="button">Click here to upload</button>
<div id="upload_form_container" title="Form container title">
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<img id="upload_preview" style="width: 300px; height: 300px;" />
<input id="upload_image" accept="image/*" type="file" name="user_img" onchange="PreviewImage();" />
<script type="text/javascript">
// This JavaScript snipppet is for previewing the image upload
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("upload_image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("upload_preview").src = oFREvent.target.result;
// document.getElementById("upload_image").disabled = true
}; // DONE: function (oFREvent)
}; // DONE: function PreviewImage()
</script>
<p>Name <input type="text" name="form1_name" /></p>
<input type="submit" value="Next" />
</form>
</div>
4) script.js
$(document).ready(function(){
var uFormContainer = $('#upload_form_container');
// This snippet is for opening the pop-under form
uFormContainer.dialog({autoOpen: false});
$('#upload_form_opener').click(function(){
uFormContainer.dialog('open');
});
});
5) I want the second step of the form to look like this...
<form action="form2" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<p>Some other text field <input type="text" name="form2_option" /></p>
<input type="submit" value="Next" />
</form>
...but I don't want to leave the page (which is '/', as far as Sinatra is concerned). Is this possible in Sinatra?
There are multiple ways to implement this:
Save some cookie or session, which step is now, and depends on that yield different forms. After submitting write next step id into session and redirect to root_url.
Use ajax to send form and render next step's form.
You can even not really send form, but just switch to next, just hidding previous fields with javascript and show next step's fields. After submitting all parameters will be sent.

Add or Delete Textbox Then Get Their Value Using PHP or Jquery

What I want to do is to allow the users to have their choice whether to add more text box when filing their data.
So far I have this code
http://code.jquery.com/jquery-1.5.1.js
This is the code that I got.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<style type='text/css'>
.Delete{color:#ff0000;}
.Add {color:green;}
.Retrieve{color:blue;}
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function(){
$('.Delete').live('click',function(e){
$(this).parent().remove();
});
$('.Add').live('click',function(e){
$('.Option:last').after($('.Option:last').clone());
});
$('.Retrieve').live('click',function(e){
$('.Option input').each(function(i,e){
alert($(e).val()); //Alerts all values individually
});
});
});
});//]]>
</script>
</head>
<body>
<div class='Option'>
<input type='text' name='txtTest'/>
<input type='text' name='txtTest'/>
<input type='text' name='txtTest'/>
<span class='Delete'>Delete</span></div>
<br/><br/>
<span class='Add'>Add Option</span>
<br/><br/>
<span class='Retrieve'>Retrieve Values</span>
</body>
</html>
That code allows me to add more text box and delete them, but my problem is I'm trying to get the value of those text box using PHP GET or PHP POST and if possible set some limit, maybe after adding 5 sets of text boxes the user will not be able to add more.
In order to post to PHP, simply wrap your HTML in a form element:
<form method="GET" action="myPage.php">
<div class='Option'>
<input type='text' name='txtTest'/>
<input type='text' name='txtTest'/>
...
</div>
</form>
Then to limit the number of .Option elements which can be added, simply declare a global variable which counts the number of .Option elements:
var optionCount = 1;
$('.Delete').live('click',function(e){
$(this).parent().remove();
optionCount--; /* Decrease optionCount. */
});
$('.Add').live('click',function(e){
if (optionCount < 5) { /* Only if optionCount is less than 5... */
$('.Option:last').after($('.Option:last').clone());
optionCount++; /* Increase optionCount. */
}
});
You must check the number of inputs in the add event.
You use form tag to transfer data to server and
you also must set "method" attribute in form tag with GET or POST
<html>
<body>
<head>
<script type='text/javascript'> $(function(){
$('.Add').live('click',function(e){
if($('.option input').length < 5)
{
$('.Option:last').after($('.Option input:last').val('').clone());
}
// Other code
// ...
}
});
</script>
</head>
<form action="welcome.php" method="post">
<input type='text' name='txtTest'/><br>
<input type='text' name='txtTest'/><br>
<input type="submit">
</form>
</body>
</html>

Categories

Resources