I am trying to have a .csv file read to a drop down in HTML. Currently with the code below, my drop down is not being populated. I am not sure if it's because of my path or if I am not calling it correctly in my HTML. Any advice?
code (I found this code as an example and was trying to implement it to test with no luck):
(function() {
var csv_path = "C:\Users\userName\Documents\Qlik\Request Page\streamFileTEST.csv";
var renderCSVDropdown = function(csv) {
var dropdown = $('select#selectStyle');
for (var i = 0; i < csv.length; i++) {
var record = csv[i];
var entry = $('<option>').attr('value', record.someProperty);
console.log(record);
dropdown.append(entry);
}
};
$.get(csv_path, function(data) {
var csv = CSVToArray(data);
renderCSVDropdown(csv);
});
}());
function CSVToArray(strData, strDelimiter) {
strDelimiter = (strDelimiter || ",");
var objPattern = new RegExp((
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
"([^\"\\" + strDelimiter + "\\r\\n]*))"
), "gi");
var arrData = [
[]
];
var arrMatches = null;
while (arrMatches = objPattern.exec(strData)) {
var strMatchedDelimiter = arrMatches[1];
if (strMatchedDelimiter.length && strMatchedDelimiter !== strDelimiter) {
arrData.push([]);
}
var strMatchedValue;
if (arrMatches[2]) {
strMatchedValue = arrMatches[2].replace(new RegExp("\"\"", "g"), "\"");
} else {
strMatchedValue = arrMatches[3];
}
arrData[arrData.length - 1].push(strMatchedValue);
}
return (arrData);
}
#selectStyle {
height: 29px;
overflow: hidden;
width: 470px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="imgQlik" src="qlik-sense-logo.png">
<hr>
<form action="mailto:emailAddress.com" method="post" enctype="text/plain">
<div>
<table id="requestTable">
<tbody>
<tr>
<td class="tdLabel">
<label>Name:</label>
</td>
<td class="tdInput">
<input type="text" id="user-name" name="display-name" pattern="[A-Za-z\s]+" maxlength="50" minlength="2" required>
</td>
</tr>
<tr>
<td class="tdLabel">
<label>Stream List:</label>
</td>
<td>
<select id="selectStyle" name="streamlistselect"></select>
</td>
</tr>
</tbody>
</table>
</div>
<input class="buttonRequest" type="submit" value="Submit Request">
</form>
1 major concept- You cannot read the filesystem through the browser due to security concerns. So doing a get request to C:\Users\userName\.... will not work.
Then just a few small things after that:
The user needs to upload the file themselves, so I added an input of type file for your users to upload their csv files. I limited it to only csv files with accept=".csv" attribute
Then you need a way to handle that file, I put together handleFile() function for you that reads in the data from the uploaded csv file using FileReader.
Next we call renderCSMDropdown with the csv data and I updated your loop a bit to loop through the elements split by a "," and append an option node to your select element. I also added a text attribute to the options so you can see them.
$("#inputFile").on("change", handleFile);
var renderCSVDropdown = function(csv) {
var dropdown = $('#selectStyle');
var elements = csv.split(",");
for (var i = 0; i < elements.length; i++) {
var record = elements[i];
var entry = $('<option>', {value: record, text: record})
dropdown.append(entry);
}
};
function handleFile() {
var file = $(this).prop('files')[0];
var fileReader = new FileReader();
fileReader.onload = function (evt) {
renderCSVDropdown(evt.target.result);
};
fileReader.readAsText(file, "UTF-8");
}
#selectStyle {
height: 29px;
overflow: hidden;
width: 470px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="imgQlik" src="qlik-sense-logo.png">
<hr>
Choose csv file: <input type="file" id="inputFile" accept=".csv"><br/><br/>
<form action="mailto:emailAddress.com" method="post" enctype="text/plain">
<div>
<table id="requestTable">
<tbody>
<tr>
<td class="tdLabel">
<label>Name:</label>
</td>
<td class="tdInput">
<input type="text" id="user-name" name="display-name" pattern="[A-Za-z\s]+" maxlength="50" minlength="2" required>
</td>
</tr>
<tr>
<td class="tdLabel">
<label>Stream List:</label>
</td>
<td>
<select id="selectStyle" name="streamlistselect"></select>
</td>
</tr>
</tbody>
</table>
</div>
<input class="buttonRequest" type="submit" value="Submit Request">
</form>
To populate dropdown, we need to set inner html of
Try below, also put the code inside document.ready function
var entry = $('<option>').html('value', record.someProperty);
Fiddle - https://jsfiddle.net/o2gxgz9r/65565/
Note - I have not used csv file but assumed that csv is read and converted to an array
Related
I am new to HTML. I have written an app, which allows user to add data and it's a local application. I have used forms int this application and I am facing a problem when form submission happens. I don't want the page to navigate/redirect and even don't want the same page to reload. Currently it's reloading the page. Please let me know what stops redirecting/reloading this app. I don't want any php code, application needs to be pure HTML and JS only.
Below is the HTML app code.
function addInfo() {
var InfoForm = document.forms["InfoForm"];
var trelem = document.createElement("tr");
for (var i = 0; i < InfoForm.length - 1; i++) {
var tdelem = document.createElement("td");
tdelem.innerHTML = InfoForm[i].value;
trelem.appendChild(tdelem);
}
document.getElementById("current_table").appendChild(trelem);
return false;
}
function done(e) {
e.preventDefault();
return false;
}
<div id="current_div">
<h2>Table Heading</h2>
<table border="1" id="current_table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</div>
<div id="input_div">
<form name="InfoForm" accept-charset="utf-8" onsubmit="done(e)">
Name :
<input type="text" name="Name" value="">
<br>
<br>Age :
<input type="number" name="Age" value="">
<br>
<br>
<input type="submit" value="Add_Info" onclick="addInfo()">
</form>
</div>
This is not the right case to use a <form>. A <form> is used when you send via GET or POST method data to the server.
Therefore just use a <button> and two <input>.
It's easier to insert a row with insertRow and insertCell.
Complete example :
var nName = document.getElementById("nName");
var nAge = document.getElementById("nAge");
var btn = document.getElementById("addData");
var tbl = document.getElementById("myData");
function addData() {
var row = tbl.insertRow(0);
var d1 = row.insertCell(0);
var d2 = row.insertCell(1);
d1.innerHTML = nName.value;
d2.innerHTML = nAge.value;
}
btn.addEventListener("click", addData);
table {
margin: 15px 0;
}
#inputData > div {
margin: 5px 0;
}
#inputData > div > span {
display: inline-block;
width: 100px;
}
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody id="myData"></tbody>
<!-- Insert data -->
</table>
<div id="inputData">
<div><span>Name:</span>
<input type="text" id="nName">
</div>
<div><span>Age:</span>
<input type="number" id="nAge">
</div>
<div>
<button id="addData">Add data</button>
</div>
</div>
A form submission made a GET/POST request to the server. You can't use only JS for get data from a form submission.
If you don't want use server side language for some simple applications you can make your own function without really submit your form.
Example without form
function gocalc()
{
var number = document.getElementById("number").value;
var text = document.getElementById("text").value;
if(number>0 && number <11 && text !="")
{
for(var i=0;i<number;i++)
{
document.getElementById("content").innerHTML=document.getElementById("content").innerHTML+"<p>"+text+"</p>";
}
}
else
alert("You must write some text and choose a number between 1 and 10");
}
Choose a number between 1 and 10 <input type="number" max="10" id="number"> <br>
Write some text <input type="text" id="text"><br>
<button onclick="gocalc()">Ok</button>
<div id="content"></div>
You can use onsubmit attribute and call your function. don't forget to return false for prevent the form submission.
Example with form
function myfunction(myform)
{
alert(myform.mytext.value);
return false;
}
<form onsubmit="return myfunction(this)">
<input name="mytext" type="text">
<button type="submit">Submit</button>
</form>
In the code below it works great to clone the table, but it doesn't go deep enough to rename the inputs of each form field in the table. For example Attendee1, Attendee2, Attendee3 etc.
Is there a way instead of just grabbing NewEl.children a way to just find all the input elements within the table then rename them?
I am not trying to add a row, I need to clone the entire table.
Any help you all out there in cyberland can give will be greatly appreciated.
<form name="EditRoster" method="post" action="DoRoster.php">
<table id="RosterTbl" cellspacing="0" cellpadding="2">
<tr style="text-align:left;vertical-align:top;">
<td><b>Name</b>:</td>
<td>
<input type="text" name="Attendee" value="" size="25" onclick="alert(this.name)">
</td>
<td><b>Paid</b>:</td>
<td>
<input type="checkbox" name="Paid" value="Yes" size="25">
</td>
</tr>
<tr style="text-align:left;vertical-align:top;">
<td><b>Email</b>:</td>
<td>
<input type="text" name="Email" value="" size="25">
</td>
<td><b>Paid When</b>:</td>
<td>
<input type="text" name="PaidWhen" value="" size="10">
</td>
</tr>
</table>
<div style="padding:5px;">
<input type="hidden" name="NumStudents" value="0">
<input type="button" name="AddPersonButton" value="Add Person" onclick="CloneElement('RosterTbl','NumStudents');">
</div>
</form>
<script language="javascript">
var TheForm = document.forms.EditRoster;
function CloneElement(ElToCloneId, CounterEl) {
var CloneCount = TheForm[CounterEl].value;
CloneCount++;
TheForm[CounterEl].value = CloneCount;
var ElToClone = document.getElementById(ElToCloneId);
var NewEl = ElToClone.cloneNode(true);
NewEl.id = ElToCloneId + CloneCount;
NewEl.style.display = "block";
var NewField = NewEl.children;
for (var i = 0; i < NewField.length; i++) {
var InputName = NewField[i].name;
if (InputName) {
NewField[i].name = InputName + CloneCount;
}
var insertHere = document.getElementById(ElToCloneId);
insertHere.parentNode.insertBefore(NewEl, insertHere);
}
}
</script>
Looked like you were on the right track, but I think you were taking a few extra steps, so I think I simplified it ;)
One thing you were missing was that the value of NumStudents is returned as a string so you have to call parseInt() on it.
var theForm = document.forms.EditRoster;
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function CloneElement(cloneID, counterName) {
var clone = document.getElementById(cloneID);
var newClone = clone.cloneNode(true);
var counter = theForm[counterName].value = parseInt(theForm[counterName].value) + 1;
// Update the form ID
newClone.id = newClone.id + counter;
// Update the child Names
var items = newClone.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
if (items[i].name != null)
items[i].name = items[i].name + counter;
}
insertAfter(clone, newClone);
}
Here's a working copy on jsFiddle.
P.s. I wasn't sure if you wanted the new fields clearing so I left them.
I have written a function in Javascript which will be fired on page load.
The function works fine for the first time. But if I come back to index page after visiting other pages, it does not work properly.
It does work correctly upto a certain point but skips code after that.
following is my function
<script>function populate() {
//alert("The Flag is "+$('#flag').val());
val =document.getElementById('flag').value;
xml =document.getElementById('xml').value;
alert(xml);
if (val === "M") {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(xml);
alert("ActiveX");
} else {
var parser = new DOMParser();
doc = parser.parseFromString(xml, 'text/xml');
// alert("DOMparser");
}
alert("Value true");
/* upto here function works correctly each time
* I have also seen the values of both val and xml are coming correctly
*/
passportNo = doc
.getElementsByTagName('PASSPORT_NO')[0].childNodes[0].nodeValue;
//alert('passportNo ' + passportNo);
document.getElementById('passportNo').value = passportNo;
pass_type = doc.getElementsByTagName('PASS_TYPE')[0].childNodes[0].nodeValue;
// alert("Pass_type = " + pass_type);
if (pass_type === "I") {
document.getElementById('in').checked = true;
} else if (pass_type === "O") {
document.getElementById('out').checked = true;
}
jobNo = doc.getElementsByTagName('JOB_NO')[0].childNodes[0].nodeValue;
//alert("jobNo = "+jobNo);
document.getElementById('job_no').value = jobNo;
jobDt = doc.getElementsByTagName('JOB_DT')[0].childNodes[0].nodeValue;
//alert("jobDT "+jobDt);
document.getElementById('DT').value = jobDt;
//Clear xml
nationality =doc.getElementsByTagName('NATIONALITY')[0].childNodes[0].nodeValue;
document.getElementById('nationality2').value = nationality;
element = document.getElementById('nationality');
element.value = nationality;
}
} </script> `
and this is how I am calling it
<body onload="populate()">
<table width="1270" align="center">
<tr>
<td width="1010" height="46" colspan="3" align="center"><h1>Currency
Declaration Form</h1></td>
</tr>
</table>
<input type="hidden" id="flag" value="<%=code%>" />
<input type="hidden" id="xml" value="<%=xml%>" />
<form name="myForm" action="Entry.do" method="post"
onsubmit="return validateAll()" class = "autocompleteOff">
<table width="1042">
<tr class="heading">
</tr>
<tr>
<td width="256" align="left"><input type="radio" name="inout"
id="in" value="I" /> <label>INCOMING </label> <input type="radio"
name="inout" id="out" value="O" /> <label>OUTGOING </label></td>
<td width="774" align="right"><label>JobNo/DT</label> <input
type="text" name="job_no" id="job_no" readonly="readonly"
tabindex="-1" /> <input type="text" name="DT" id="DT"
readonly="readonly" tabindex="-1" value="<%=Convert.getSysDate()%>" /></td>
</tr>
</table>`
I can't see neither passportNo id neither PASSPORT_NO tag (getElementsByTagName) in your HTML code. Same problem with pass_type, nationality and many other elements. Do you miss some code? Or, maybe, this is dynamic output from PHP (for example) and after first run it returns different HTML?
I am developing this for use in Internet Explorer 8 (because at work we have to use it). I have a page that has a table withing a form. The table has a button to "clone" rows, "AddScheduleRow()". That part works good. Each row has a button to delete that row "DeleteRow(r)". That part works well too. I also have a script to rename/renumber each row, "RenumberRows()". It almost works good. I can rename the text fields (for example what was previously StartDate3 now becomes StartDate2). However, in each row is an input that is type="image" and it is named like you should with any input. The name of it is "StartDateCal". The problem is that during the renaming process, when it hits the image input (TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;), I get a JavaScript error "'TheForm.StartDateCal' is null or not an object". I cannot figure this one out and it's standing in the way of moving on.
What can I do to try to rename an < input type = image /> ?
Below is the necessary code:
HTML
<html>
<head>
</head>
<body>
<form name="UpdateSchedule" method="post" action="DoSchedule.asp">
<input type="hidden" name="NumRows" value="0">
<input type="hidden" name="RowsAdded" value="0">
<table id="ClassScheduleTable">
<tr id="ScheduleRow" style="display:none;">
<td>
<input type="text" name="RowNum" value="0" size="1" onclick="alert(this.name)">
</td>
<td>
<b>Start Date</b> <input type="text" name="StartDate" value="" onclick="alert(this.name);" size="8">
<input type="image" name="StartDateCal" src="http://www.CumminsNorthwest.com/ATT/Img/Calendar3.png" style="border-style:none;" onClick="alert('name = ' + this.name);return false;">
</td>
<td>
<input type="button" value="Del." name="DelRow" class="subbuttonb" onclick="DeleteRow(this);">
</td>
</tr>
<tr>
<td colspan="3" style="text-align:right">
<input type="button" value="Add Class Date" class="SubButton" onclick="AddScheduleRow();">
</td>
</tr>
</table>
</form>
</body>
<script language="JavaScript">
JS
var TheForm = document.forms.UpdateSchedule;
var NumRows =0;
var RowsAdded =0;
function AddScheduleRow(){
NumRows++;
TheForm.NumRows.value = NumRows;
RowsAdded++;
TheForm.RowsAdded.value = RowsAdded;
var TableRowId = "ScheduleRow";
var RowToClone = document.getElementById(TableRowId);
var NewTableRow = RowToClone.cloneNode(true);
NewTableRow.id = TableRowId + NumRows ;
NewTableRow.style.display = "table-row";
var NewField = NewTableRow.children;
for (var i=0;i<NewField.length;i++){
var TheInputFields = NewField[i].children;
for (var x=0;x<TheInputFields.length;x++){
var InputName = TheInputFields[x].name;
if (InputName){
TheInputFields[x].name = InputName + NumRows;
//alert(TheInputFields[x].name);
}
var InputId = TheInputFields[x].id;
if (InputId){
TheInputFields[x].id = InputId + NumRows;
//alert(TheInputFields[x].id);
}
}
}
var insertHere = document.getElementById(TableRowId);
insertHere.parentNode.insertBefore(NewTableRow,insertHere);
RenumberRows();
}
AddScheduleRow();
function DeleteRow(r){
var i=r.parentNode.parentNode.rowIndex;
document.getElementById("ClassScheduleTable").deleteRow(i);
NumRows--;
TheForm.NumRows.value = NumRows;
RenumberRows();
}
function RenumberRows(){
var TempCounter = 0;
for (var i=0;i<=RowsAdded;i++){
if (TheForm.RowNum[i]){
TempCounter++;
TheForm.RowNum[i].name = "RowNum" + TempCounter;
TheForm.RowNum[i].value = TempCounter;
TheForm.StartDate[i].name = "StartDate" + TempCounter;
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
}
}
}
</script>
</html>
might be to do with your DTD,
try HTML4 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
You can use
document.getElementsByName('StartDateCal')[i].name = "StartDateCal" + TempCounter;
instead of
TheForm.StartDateCal[i].name = "StartDateCal" + TempCounter;
The code below fetches a list of files that have been selected for upload.
It basically appends input elements inside a div above a form element:
<div id = "files_list"> </div>
How do I store all the attributes names in an array - fileNamesArray - on clicking the submit button.?
My attempt I'm yet to check if this works:
// beginning of attempt
// my approach:
// alert the user if no file is selected for upload and submit is clicked else
// I'd have to iterate through the input elements and contained in the div id="files_list", fetch all the file names and push all the values into an array $filesArray.
//rough attempt
$("Submit").click(function () {
$filesArray
$(div#files_list).getElementById('input').each(function($filesArray) {
filesArray.push($this.attr("value"))
});
while( $filesArray.size != 0) {
document.writeln("<p>" + $filesArray.pop() + "</p>");
}
}
//end of attempt: I print out the names just to verify
Code Below:
$(document).ready(function(){
var fileMax = 6;
$('#asdf').after('<div id="files_list" style="border:1px solid #666;padding:5px;background:#fff;" class="normal-gray">Files (maximum '+fileMax+'):</div>');
$("input.upload").change(function(){
doIt(this, fileMax);
});
});
function doIt(obj, fm) {
if($('input.upload').size() > fm) {alert('Max files is '+fm); obj.value='';return true;}
$(obj).hide();
$(obj).parent().prepend('<input type="file" class="upload" name="fileX[]" />').find("input").change(function() {doIt(this, fm)});
var v = obj.value;
if(v != '') {
$("div#files_list").append('<div>'+v+'<input type="button" class="remove" value="Delete" style="margin:5px;" class="text-field"/></div>')
.find("input").click(function(){
$(this).parent().remove();
$(obj).remove();
return true;
});
}
};
Code for the HTML form:
<td><form action="test.php" method="post" enctype="multipart/form-data" name="asdf" id="asdf">
<div id="mUpload">
<table border="0" cellspacing="0" cellpadding="8">
<tr>
<td><input type="file" id="element_input" class="upload" name="fileX[]" /></td>
</tr>
<tr>
<td><label>
<textarea name="textarea" cols="65" rows="4" class="text-field" id="textarea">Add a description</textarea>
</label></td>
</tr>
<tr>
<td><input name="Submit" type="button" class="text-field" id="send" value="Submit" /></td>
</tr>
</table><br />
</div>
</form>
<p class="normal"></td>
var my_array = new Array();
$('#asdf').bind('submit', function() {
$.each(this.elements, function() {
if ( this.type == 'file' ) {
$('#file_list').append($(this).clone());
my_array.push(this.value);
}
});
for ( var i=0; i < my_array.length; i++ )
alert(my_array[i]);
});
Here you go!
EDIT Updated due to OP's comment.