iterating through imput elements to assign values to an array - javascript

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.

Related

How can I list all values stored in a JS array using a button click?

I'm attempting to teach myself JavaScript and was wondering if it was possible to feed values into an array, then have those values listed out inside an HTML element, upon an on-click event?
This is what I'm trying currently :
<table>
<tr>
<td>
<form onsubmit="storeItems()">
Enter value :
<input type="text" id="box">
<br/><br/>
<input type="submit" value="Submit">
<br/><br/>
<button type="button" onclick="listItems()" id="show">Show stored values</button>
</form>
</td>
</tr>
</table>
<div id="showbox"></div>
var items = [];
function storeItems() {
valueBox = document.getElementById('box').value;
items.push(valueBox);
return false;
}
function listItems() {
var x;
for (x of items) {
document.write(x + "<br>");
}
}
</script>
I would appreciate any help.
Thank you :)
<table>
<tr>
<td>
<form>
Enter value :
<input type="text" id="box">
<br/><br/>
<input type="button" value="Submit" onclick="storeItems()">
<br/><br/>
<button type="button" onclick="listItems()" id="show">Show stored values</button>
</form>
</td>
</tr>
</table>
<div id="showbox"></div>
<script>
var items = [];
function storeItems() {
valueBox = document.getElementById('box').value;
items.push(valueBox);
document.getElementById('box').value="";
return true;
}
function listItems() {
var x;
for (x of items) {
document.write(x + "<br>");
}
}
</script>
Call the function on click of the click of the button not on the submission of the form
var items = [];
function storeItems() {
valueBox = document.getElementById('box').value;
items.push(valueBox);
return false;
}
function listItems() {
var x;
for (x of items) {
document.write(x + "<br>");
}
}
<table>
<tr>
<td>
<form>
Enter value :
<input type="text" id="box">
<br/><br/>
<input type="button" value="Submit" onclick="storeItems()">
<br/><br/>
<button type="button" onclick="listItems()" id="show">Show stored values</button>
</form>
</td>
</tr>
</table>
<div id="showbox"></div>

Reading a CSV file to a HTML drop down

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

jQuery: Script isn't preventing submit function from firing when form has errors

Essentially, I am trying to have my form clear all input fields on submit if the default values are still present. Then if there are default values still present, then the submit process is stopped. The form clears the fields on submit, but wont stop the submit button from executing like its suppose to. Please help me out on this. I wrote this myself, and still trying to figure out why it isn't working.
The jQuery Script Below:
<script type="text/javascript" >
$(document).ready(function(){
$(".forms").each(function(){
var DefaultValue = $(this).value;
$("#Form_1").submit(function(){
if ( CheckInput() == "empty" ){
return false;
}
});
function CheckInput(){
var x = '';
$(".forms").each(function(){
if ($(this).value == DefaultValue){
this.value = '';
var y = "empty";
return y;
}
x = y;
return x;
});
}
});
});
</script>
The HTML code below:
<form id="Form_1">
<table>
<tr>
<td>
<table cellpadding="2" cellspacing="3" width="500px">
<tr>
<td>
<div class="InputContainer">
<input name="FirstName" value="First Name" class="forms" type="text"required="true" ></input>
<div class="InfoBlurp">First Name<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="BirthDate" value="Birth Date(MM/DD/YYYY)" class="forms" type="text" required="true" ></input>
<div class="InfoBlurp">Birth Date(MM/DD/YYYY)<div class="InfoTip"></div></div></div>
</td>
<td>
<div class="InputContainer">
<input name="Email" value="Email#sample.com" validType="email" class="forms" type="text" required="true"/></input>
<div class="InfoBlurp">Email#sample.com<div class="InfoTip"></div></div></div>
</td>
</tr>
</table>
<input id="Button_1" class="topopup" type="submit" value="" style="background-color: #FFFFFF; border:none; cursor:pointer;">
</form>
Your checkInput method is not returning anything, you are returning values from the each callback function not from the CheckInput method.
$(document).ready(function () {
$(".forms").each(function () {
var DefaultValue = $(this).value;
$("#Form_1").submit(function () {
if (CheckInput() == "empty") {
return false;
}
});
function CheckInput() {
var x = '';
$(".forms").each(function () {
if ($(this).value == DefaultValue) {
this.value = '';
x = "empty";
//return false to stop further iteration of the loop
return false;
}
});
return x;
}
});
});

Form submission cancel using javascript not working

OBJECTIVE:
I have made a form containing 3 fields, I want that If there's even a single empty field left in form
the form , it is recognised and an error message(for each empty field) is printed (not alerted), and form submission is cancelled. The error msg is initially hidden and it should be made visible only when a field is left empty.
PROBLEM:
the code to stop submission is not working.
Please post any error. It works if use only alert(), and remove the code to show and delete hidden validaeFormOnSubmit() and validateEmpty().
FORM:
<form action="start.php" method="post" onsubmit="return validateFormOnSubmit(this)" >
<table>
<tbody>
<tr>
<td><label for="fname">Team Name:</label><br></td>
<td><input name="fname" type="text" autocomplete="off">&nbsp <div id="1"> Field is
required
</div></td>
</tr>
<tr>
<td><label for="contact">Contact 1 :</label> </td>
<td><input type="text" maxlength = "10" name="contact" > &nbsp<div id="2"> Field
is required </div></td>
</tr>
<tr>
<td><label for="contact2">Contact 2:</label> </td>
<td><input type="text" maxlength = "10" name="contact2" >&nbsp <div id="3"> Field is
required </div></td>
</tr>
<tr>
<td> </td>
<td><input name="Submit" value="Send" type="submit" ></td>
<td> </td>
</tr>
</tbody>
</table>
</form>
SCRIPT
<script >
$(document).ready(function () {
var i;
for(i=1;i<=3;i++)
{
var k='#'+i;
$(k).hide();}
});
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty(theForm.fname,1);
reason += validateEmpty(theForm.contact,2);
reason += validateEmpty(theForm.contact2,3);
if (reason != "") {
return false;
}
return true;
}
function validateEmpty(fld,k) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "error";
var k='#'+i;
$(k).show();
} else {
fld.style.background = 'White';
var k='#'+i;
$(k).hide();
}
return error;
}
</script>
I would suggest the following:
Remove the onsubmit="..." from your HTML
Bind to the onsubmit event programmatically:
$(...).on("submit", validateFormOnSubmit);
Change the signature of validateFormOnSubmit accordingly:
function validateFormOnSubmit(event) {
// use this instead of theForm
}
Instead of returning false do event.preventDefault(), i.e.:
if (reason != "") {
event.preventDefault();
}
What about this ?
http://jsfiddle.net/45Kfy/
<code>
$(document).ready(function () {
$("input").each(function(index, item)
{
if ($(item).val().length == 0)
{
$(item).css("background-color", "red");
}
});
});
</code>
Instead of documentReady() you should trigger the button click.
(jQuery get the input value in an .each loop)
And watch out, your button is an inputfield too.

Javascript onload event function is working only on server restart

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?

Categories