Assign value to an hidden text input with JS - javascript

i'm a newbie of JavaScript.
I have that :
HTML:
<form>
<t:inputFileUpload required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />
<h:commandButton class="btn btn-primary" value="Upload"
action="#{controller.upload}" />
</form>
javascript:
<script>
function uploadOnChange() {
document.getElementById('upload').onchange = name;
var filename = name;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
</script>
All I want to do is get through a inputFileUpload, to browse my directory, the filename that i've selected, and pass this name as a string to jsf controller.
Does anyone can help me?
EDIT :
If I add to my form enctype="multipart/form-data seems that the controller method "upload" does nothing.

Assuming <t:inputFileUpload> has a value attribute, I'd change the code to something like this:
function uploadOnChange() {
var filename = document.getElementById('upload').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
document.getElementById('filename').value = filename;
}
console.log('Value hidden input: ' + document.getElementById('filename').value);
}
<input type="file" required="true" id="upload" onchange="uploadOnChange()" />
<input id="filename" type="hidden" />

Related

How clear the form inputs after submission?

Already tried everything from different references but, I can't get it to work. I intended to use it for google photo submission form. I just want my text inputs and textarea to clear after it successfully uploaded everything.
Here's the whole HTML code.
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName"
placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection"
placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
<br>
<br>
<div id="output"></div>
<script>
var rootFolderId = 'xxxxxxxxxxxxxxxxxxx';
var numUploads = {};
numUploads.done = 0;
numUploads.total = 0;
// Upload the files into a folder in drive
// This is set to send them all to one folder (specificed in the .gs file)
function uploadFiles() {
var allFiles = document.getElementById('filesToUpload').files;
var applicantName = document.getElementById('applicantName').value;
if (!applicantName) {
window.alert('Missing applicant name!');
}
var gradesection = document.getElementById('gradesection').value;
if (!gradesection) {
window.alert('Missing Grade & Section!');
}
var folderName = applicantName + ' - ' + gradesection;
if (allFiles.length == 0) {
window.alert('No file selected!');
} else {
numUploads.total = allFiles.length;
google.script.run.withSuccessHandler(function(r) {
// send files after the folder is created...
for (var i = 0; i < allFiles.length; i++) {
// Send each file at a time
uploadFile(allFiles[i], r.folderId);
}
}).createFolder(rootFolderId, folderName);
}
}
function uploadFile(file, folderId) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
document.getElementById('output').innerHTML = 'uploading '
+ file.name + '...';
//window.alert('uploading ' + file.name + '...');
google.script.run.withSuccessHandler(onFileUploaded)
.uploadFile(content, file.name, folderId);
}
reader.readAsDataURL(file);
}
function onFileUploaded(r) {
numUploads.done++;
document.getElementById('output').innerHTML = 'uploaded '
+ r.fileName + ' (' + numUploads.done + '/'
+ numUploads.total + ' files).';
if (numUploads.done == numUploads.total) {
document.getElementById('output').innerHTML = 'All of the '
+ numUploads.total + ' files are uploaded';
numUploads.done = 0;
}
}
</script>
The form upload and displays the response to the user.
I want to reset the form so, the form resets to its original state, so when the user upload another file it wont upload the same file again. Right now, the submission message stays and I have no clue on how to reset the form.
I am new to javascript and I have no clue on what to call to rest the form, any idea? TIA Guys :)
As your code snippet only contains input, You can find all inputs using querySelectorAll and reset its value.
Example below. When you click the button it resets all the input.
function resetAllInput() {
const allInput = document.querySelectorAll('input');
allInput.forEach( input => {
input.value = "";
})
}
function uploadFiles() {
console.log('uploading files');
resetAllInput();
console.log('Resetted all inputs');
}
<form id="uploaderForm">
<label for="uploaderForm">Photo Upload Form</label>
<div>
<input type="text" name="applicantName" id="applicantName" placeholder="Your Name">
</div>
<div>
<input type="text" name="gradesection" id="gradesection" placeholder="Your Grade Level & Section">
</div><br>
<div>
You can select multiple Photos upload!<br>
<br>
<input type="file" name="filesToUpload" id="filesToUpload" multiple>
<br><br>
<input type="button" value="Submit" onclick="uploadFiles()">
</div>
</form>
You can assign null value to your input element:
const reset = () => {
let fileInput = document.getElementById('file-input');
fileInput.value = null;
}
<input type="file" id="file-input">
<button onclick="reset()">Reset</button>

Generating JSON String from Form

I am new to JSON and trying hard to understand it's working.
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID">
<button type="submit" class="btn btn-success" >Submit Data</button>
</form>
JSON String to be generated as:
{"latency":1.6,"throughput":6.01,"outUID":{"V_ID":"40"},"inUID":{"V_ID":"16"}}
Here's the form and JSON String to be generated
Could some one guide me how do I create that nested JSON object?
Since it looks like you want the values of outUID and inUID to be nested for some reason you'll need to build the object manually. Here's a simple example:
var $latency = $('#latency'),
$throughput = $('#throughput'),
$outUID = $('#outUID'),
$inUID = $('#inUID');
var myJSONObject = {
latency:$latency.val(),
throughput:$throughput.val(),
outUID:{
V_ID:$outUID.val()
},
inUID:{
V_ID:$inUID.val()
}
};
var stringJSON = JSON.stringify(myJSONObject);
Pure javascript example
var els=document.getElemtById('edge').getElementsByTagName('input');
or
var els=document.querySelectorAll('input[class=input-"xlarge"]');
to get the elements
then
var array=[]
for(var a=0,b;b=els[a]; ++a){
array[a]=b.value
}
array is the json object
JSON.styringify(array)
is the json string
tip: if you plan to use this with ajax
there is a new way called FormData();
so:
var fd=FormData(document.getElemtById('edge'));
contains the whole form , including files
This code allow you to add more fields if required to do so without hard coding the field attributes
http://jsfiddle.net/6vQY9/
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID" data-prop="V_ID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID" data-prop="V_ID">
<button type="submit" class="btn btn-success">Submit Data</button>
</form> <pre></pre>
JS
function submit() {
var JSONString = "";
jQuery('#edge input').each(function () {
var that = jQuery(this);
var val = that.val();
var partJSON = "";
var quote = "\"";
if (that.data('prop')) {
partJSON = "{ " + quote +that.data('prop') + quote+ " : " + quote + val + quote + " }";
} else {
partJSON = val;
}
var comma = that.next('input').length > 0 ? "," : "";
partJSON = quote + that.prop('id') + quote + ":" + partJSON + comma;
JSONString += partJSON
});
JSONString = "{ " + JSONString + " }";
jQuery('pre').text(JSONString);
}

Get value of upload fields and counting the array

I have the following html code :
<form name="uploadForm" action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="file" name="file_sub[]" />
<input type="button" onClick="javascript:submitform();" value="SUBMIT BTN" />
</form>
and here is the javascript function submitform() :
function submitform()
{
var minUpload = 1;
var uploadNo;
var count=document.uploadForm.file_sub.length;
for(a=0;a<count;a++)
{
if(document.uploadForm.file_sub.value != '')
{
uploadNo++;
}
}
if(uploadNo > minUpload){
document.uploadForm.submit();
}else{
alert('Please Upload Atleast ' + minUpload + ' files');
}
}
the javascript is suppose to validate and make sure atleast minUpload of the the file fields a file inside them.
but for some reason when I try to get the length of the file in the function I get an error (according to the debugger of chrome, I get "Uncaught TypeError: Cannot read property 'length' of undefined" ) however I have tried the same thing with checkboxes and it works just fine. What am I doing wrong? is it even possible to do such task in js?
You have to refer to file_sub[]. Fixed function:
var count = document.uploadForm["file_sub[]"].length;
function submitform(){
var minUpload = 1;
var uploadNo;
var files = document.forms['uploadForm']["file_sub[]"];
var count = files.length;
for(var a=0; a<count; a++){
if(files[a].value != ''){
uploadNo++;
}
}
if(uploadNo > minUpload){
document.forms['uploadForm'].submit();
} else {
alert('Please Upload Atleast ' + minUpload + ' files');
}
}

Pass filename from file upload to text field

I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.
Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/
HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}
A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources