I have a web application with a form and an number of inputs:
<form action="">
Title1:<br>
<input type="text" name="title1">
<input type="text" name="title1Description">
<br>
Title2:<br>
<input type="text" name="title2">
<input type="text" name="title3Description">
<br>
Title3:<br>
<input type="text" name="title3">
<input type="text" name="title3Description">
<br>
<button type="button">Insert an Generate!</button>
</form>
I also have a JavaScript file which acts as a template:
template.js
function myFunction(p1, p2) {
return p1 * p2;
}
function mySecondFunction(p3, p4) {
return p3 - p4;
}
var myData = {
*title1* : {
Title: *title1*,
Description: *title1Description*
},
*title2* : {
Title: *title2*,
Description: *title2Description*
},
}
When a user clicks the button, how can i generate a copy of template.js insert the values the user has entered into the xxxxx parts of var myData, and prompt the user to download the newly generate file?
I can use AngularJS if this makes it easier than jQuery?
I'm not going to write the entire code, but here's what I'm thinking about:
When the button is clicked, you could pass the values e.g. using GET variables. Click here to find out how that works.
Next you can save the entire code of the js file in a String, and use the values from the GET variables.
And last but not least, use the following code to download a file containing the generated String str:
window.open('data:text/csv,' + encodeURIComponent(str));
Edit
The solution above doesn't make it possible to store the file with a custom file name. If you want to accomplish that, you would need a little work around, because you need to use the download attribute of <a>:
var link = document.createElement("a");
var csv = "data:text/csv;charset=utf-8," + str;
link.setAttribute("href", encodeURI(csv));
link.setAttribute("download", "template.js"); //custom file name here
link.click();
Be aware that not every browser supports the download attribute. Check here to find out more.
Edit2
Okay, I wrote the code, because I was having a good day and not much to do ;) You can find it here (jsFiddle was giving me troubles)
Related
I am currently working on a python program that uses a html/css interface which is connected through eel. It requires the user to load a file to analyze. In order to show the user on the User interface which file was selected, I want to show the name of the file (or the path) after the selection process is done.
Since I am new to this, I found a simple filedialog on the internet (probably somewhere here on Stackoverflow) that uses JQuery to select the path to a file. The selection works fine and my program can work with that information if the file that is being selected is located in the same folder as the html file, as this circumvents fakepath errors and I do not know a way around it.
I want to display the selected path underneath the button once it has been selected. However, in the current configuration it displays [object object] right after clicking the "Browserino" button and not the selected path or (ideally) the selected filename.
The HTML document contains:
<div class="col">
<button id="button" class="btn btn-primary" onclick="clicked();">Browserino</button>
<input id="file-input" type="file" name="name" style="display: none;" />
<small id="pathway" class="form-text text-muted">invisible</small>
</div>
And the main.js has this function to work with:
function clicked(){
var path = String($('#file-input').trigger('click'));
document.getElementById('pathway').innerHTML = path;
document.getElementById('pathway').style.visibility = 'visible';
}
I have also tried the follwing in the main.js, but it does not do the trick for me:
function clicked(){
String($('#file-input').trigger('click'));
var file_input = document.getElementById('file-input').value;
var filepath = file_input.replace(/^.*[\\\/]/, '');
document.getElementById('pathway').innerHTML = filepath;
}
Thanks for all the comments before, I hope this edit helps clarify the problem. Any help is appreciated. Thx.
I am trying to retrieve simple javascript variable (which is written to a File Systems Object) from a website which is served by an apache host on my ubuntu laptop.
So I have the function that writes the variable set up as follows:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("/home/lex/Downloads/goal.txt", true);
s.writeline(document.passForm);
s.Close();
}
</script>
and the section that takes the user input from the html website is
<div id="bot-right">
<form onsubmit="WriteToFile(this['goal'].value)">
<a align = "left"> <b><Strong>Enter a Goal name</Strong></b></a><br>
<input type="text" name="goal"> <br>
<input type="submit" value="Send Zeus">
<br>
</form>
</div>
For some reason, when I type in variable names to the form on the website, the file goal.txt gets created in the directory, /home/lex/Downloads/, but nothing gets written to it.
I also noticed that when I delete the goal.txt file and rewrite the variable from the html website, the file doesn't always get created.
I am not a JavaScript person and I am at a loss as to what I may need to fix this.
My intention is to get the variable written to the text file and have a processing c++ file process the variable.
Would someone be kind enough to lend an insight?
Thanks!
one way to do it is just calling the function without parameters and just getting the input value like this:
adding and id or a class to your input to get that specific value:
document.getElementById('goal').value
document.getElementByClass('goal').value
Or getting the value by name:
document.querySelector('[name="goal"]').value;
EDIT1
You could add a console.log to check if the value is beign passed correctly like this:
var inputValue = document.querySelector('[name="goal"]').value;
console.log(inputValue);
And if the value is being passed then the problem is your writeline or in the creation of the document
EDIT2
I just tested it and retrieving the value works just fine, so the problem must be in your document writing method, please check this documentation it can help you and i think is a better solution:
http://www.html5rocks.com/en/tutorials/file/filesystem/
I've been having a rather large amount of trouble doing what I imagine to be quite a simple task. I've looked through SO and various pieces of documentation though nothing I try seems to work, thus I thought to post here.
What I'm trying to do is to handle my html form (templated through JADE), and save all data from specific inputs (name="ListContent[]") into a singular array, with one value in the array per input. I'm needing to take this approach because the number of listContent inputs is dynamic, and I do not know how many will need to be handled.
My form looks something like this:
<form method='post'>
<input name='listTitle'></br>
<input name='listDescription'></br>
<input name='listContent[]'></br>
<input name='listContent[]'></br>
...
...
<input name='listContent[]'></br>
<input name='listContent[]'></br>
<input name='listContent[]'></br>
<button type='button' onClick='addInput('listContent');'>
<button type='submit'>
</form>
This is rendered as a form like this;
I'm able to retrieve the POSTed values of listName and listDescription as follows, though I'm at a loss for how to process the listContent and save all inputs into an array like:
"{'line 1', 'line 2', 'line 3'}"
var listName = form.data.listName; // Works
var description = form.data.listDescription; // Works
var contentRaw = form.data.listContent; // Just returns blank
Any advice would be appreciated. Thanks!
EDIT:
I'm using npm forms (https://www.npmjs.com/package/forms) to parse /process my form data. My defined form schema is as follows:
var simpleNewListForm = forms.create({
listToken: forms.fields.string({
required:true
}),
listName: forms.fields.string({
required: true
}),
listDescription: forms.fields.string({
required: true
}),
listContent: forms.fields.array(),
});
I see that you use listContents while creating the form, but listContent while accessing it after parsing it. When I tried generating the form with the same code you showed, the input name for listContents is listContents itself in the generated HTML form.
I need to implement an export to Excel function, but only for selected lines of the jtable, in a JSP environment.
My question is: what is the best way to do it? From the jtable, I pick the $('#SearchResultTable').jtable('selectedRows') and post it (using jquery $.post() ) to my servlet (that is generating the Excel file using poi). Everything good until I have to pick up the response from the servlet. Turns out I cannot save it to disk or prompt the browser to download it, since ajax is basically javascript, and thus have no access to the disk.
Is there a better way to do this? I want to be able to name and save the resulting file.
This is my call function which handles the post:
toolbar: {
items: [{
icon: 'art/excel_ico.gif',
text: 'Esporta in Excel',
display: 'download="Report.xls"',
click: function() {
return $.post("ExcelExport", {n: "Magazzino", t: $('#SelectedRowList')[0].innerHTML})
.done(function(data) {
alert("Data Loaded: " + data);
});
}
}]
},
Thank you for your help,
Fabio.
Solved.
I used a form instead of the "toolbar:" item in JTable. To whoever may be interested:
I removed the "toolbar" item from JTable init function.
Added a form to the page, like this:
<div id="formWrapper">
<form id="exportForm" action="ExcelExport" method="post">
<input type="hidden" value="" name="exportRows" id="exportRows">
<input type="hidden" value="Ordini" name="dataType" id="dataType">
<input type="submit" value="Esporta">
</form>
</div>
Styled the form using css to make it look like the button on the JTable toolbar.
In the JTable init, I added a selectionChange item, like this:
selectionChanged: function() {
var $selectedRows = $('#SearchResultTable').jtable('selectedRows');
$('input:hidden[name="exportRows"]').val("");
$selectedRows.each(function() {
var record = $(this).data('record');
$('input:hidden[name="exportRows"]').val($('input:hidden[name="exportRows"]').val()
+ record.id. ... );
});
}
So every time I change something on the JTable selection, the value of exportRows changes.
The form points to my servlet that can then send back the data as an Excel file, which I can name and save.
Hope it helps.
Fabio.
I had an issue with copying a value from one form to another via JavaScript, which I was able to figure out with help from my previous question here: "How to copy a value from one form's file upload field to another form's text field?"
So, thank you!
But now I have a new issue. When the form field value is copied over, in some browsers (such as IE), the field contains the local path of the field on the user's computer (i.e. "C:\Users\username\Desktop\file.png"), which obviously won't work in the URL.
So: is there a way to filter out everything but the file name itself before it's copied to the new field? Or a way to do it after the fact?
Thanks for the help!
Here is my most recent simplified code for this:
<script>
$(function(){
bindGroups();
});
var bindGroups = function() {
// First copy values
$("input[name='logofile']").val($("input[name='logoname']").val());
// Then bind fields
$("input[name='logoname']").change(function() {
$("input[name='logofile']").val($(this).val());
});
};
</script>
<form action="/current-url" method="post" enctype="multipart/form-data">
<input type="file" name="logoname" value="1" />
<input type="submit" value="Upload" />
</form>
<form name="create_landing_page" action="/landing-page-url/" method="get">
<input type="hidden" name="logofile" />
<input type="submit" value="Generate Landing Page" /></form>
Try using a combination of split() and pop();
var basename = fullFileName.split('\\').pop();
Note the double backslash to escape the slash; this will only fix the problem for Windows browsers, because Linux/OS X uses a slash (/) as directory separator, so might try this (untested as I'm on my iPad at the moment)
var basename = fullFileName;
if (indexof('\\', basename) >= 0) {
basename = basename.split('\\').pop();
}
if (indexof('/', basename) >= 0) {
basename = basename.split('/').pop();
}
Try this:
var field = $(this).val();
var index = field.lastIndexOf("\");
field = field.substr( index, field.length-index );
I finally figured this out, and it was simpler than I had hoped. All I had to do was change the line:
$("input[name='logofile']").val($(this).val());
to:
$("input[name='logofile']").val($(this).val().split('\\').pop());
The problem with using a variable was that I had to refresh it when the upload field changed, which wasn't hard; I refreshed the variable when the upload button was clicked. But for some reason, when I replaced $("input[name='logoname']") with my variable name, the value wouldn't copy over. I couldn't figure it out.
This ended up being much simpler, no variables needed. Split/pop did the job, so thanks everyone who suggested it! You pushed me in the right direction.