Adding file inputs dynamically with jquery? - javascript

To make my weppage as compatible as possible I will go with the regular file input, the problem is that I need to offer multiple uploads.
My thought is that when the first input is set a second will be shown (up to a max of 10). Say that we have filled 5 and there is 6 visible. We now clear the second input, this will result in two empty inputs so then the last(6(empty)) input should be hidden.
Is this possible to to with Jquery?
Edit1: This is what I manage to create, it works fine. I am however sure that someone that know jquery better could make a smarter script:
In the view:
<div id="fileInput0" class="fileVisible">
<input type="file" id="file0" name="files" />
<input type="button" value="Töm" onclick="resetFileField(0)" />
</div>
<div id="fileInput1" class="fileHidden">
<input type="file" id="file1" name="files" />
<input type="button" value="Töm" onclick="resetFileField(1)" />
</div>
<div id="fileInput2" class="fileHidden">
<input type="file" id="file2" name="files" />
<input type="button" value="Töm" onclick="resetFileField(2)" />
</div>
<div id="fileInput3" class="fileHidden">
<input type="file" id="file3" name="files" />
<input type="button" value="Töm" onclick="resetFileField(3)" />
</div>
<div id="fileInput4" class="fileHidden">
<input type="file" id="file4" name="files" />
<input type="button" value="Töm" onclick="resetFileField(4)" />
</div>
<div id="fileInput5" class="fileHidden">
<input type="file" id="file5" name="files" />
<input type="button" value="Töm" onclick="resetFileField(5)" />
</div>
<div id="fileInput6" class="fileHidden">
<input type="file" id="file6" name="files" />
<input type="button" value="Töm" onclick="resetFileField(6)" />
</div>
<div id="fileInput7" class="fileHidden">
<input type="file" id="file7" name="files" />
<input type="button" value="Töm" onclick="resetFileField(7)" />
</div>
<div id="fileInput8" class="fileHidden">
<input type="file" id="file8" name="files" />
<input type="button" value="Töm" onclick="resetFileField(8)" />
</div>
<div id="fileInput9" class="fileHidden">
<input type="file" id="file9" name="files" />
<input type="button" value="Töm" onclick="resetFileField(9)" />
</div>
The Script:
function fileChangeHandler() {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var parentDiv = $(this).parent;
var idNr = $(this).attr('id').replace('file', '');
idNr++;
if($(this).val().length > 0){
for(var i = idNr; i < 10; i++){
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){ return;}
}
else{
$('#fileInput' + i).attr('class' , visibleClass);
return;
}
}
}
}
function resetFileField(id) {
var hiddenClass = 'fileHidden';
var visibleClass = 'fileVisible';
var counter;
$('#fileInput'+id).html($('#fileInput'+id).html());
$('#file'+id).change(fileChangeHandler);
for(var i = 9; i > -1 ;i--)
{
if(id != i)
{
if($('#fileInput' + i).hasClass(visibleClass)){
if($('#file' + i).val().length < 1){
$('#fileInput' + i).attr('class', hiddenClass);
}
}
}
}
}
What is a better solution?

You could have a container div which will harbor the new file input fields and a button to add new inputs:
$('#addFile').click(function() {
// when the add file button is clicked append
// a new <input type="file" name="someName" />
// to a filesContainer div
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'someName')
);
});

Yes, you can just add a file input to the form as you would any other element:
$("#theForm").append("<input type='file' name='foo'>");
I thought this sounded familiar: [jquery]How do I add file uploads dynamically?

Another option, since you are using JQuery is the Bootstrap fileInput. It lets you upload multiple images with one control. You have additional options too like the allowed file types, size, height, width, etc.
<script type="text/javascript">
$("#postedImage").fileinput({
uploadUrl: "/SomeUrl", // you must set this for ajax uploads
maxFileCount: 10,
enctype: "multipart/form-data",
overwriteInitial: false
});
</script>
<input id="postedImage" type="file" class="file" multiple>
Here is a link for other uploaders if you are interested.

if you want to have diffrent input names
var i;
$('#addFile').click(function() {
i=i+1;
$('#filesContainer').append(
$('<input/>').attr('type', 'file').attr('name', 'file'+i)
);
});

Related

Adding elements dynamically

I'm trying to add elements dynamically through javascript but whenever I try opening up the page they appear for a split second then disappear
I take a number of process from the input tag and run a loop to create each element individually
I tried removing everything from the event and only call a function which I placed the code in but didn't work
const numberOfProcesses = document.getElementById("numberOfProcesses").value;
const timeQuantum = document.getElementById("timeQuantum").value;
const start = document.getElementById("start");
const processDiv = document.getElementById("processDiv");
const burstDiv = document.getElementById("burstDiv");
start.addEventListener("click", (event) => {
for (let i = 0; i < numberOfProcesses; i++) {
let pLabel = document.createElement("label");
pLabel.setAttribute("id", `process ${i}`);
pLabel.innerText = `Process ${i}`;
let pInput = document.createElement("input");
pInput.setAttribute("type", "number");
pInput.setAttribute("id", `process ${i}`);
let bLabel = document.createElement("label");
bLabel.setAttribute("id", `burstTime ${i}`);
bLabel.innerText = `Burst Time ${i}`;
let bInput = document.createElement("input");
bInput.setAttribute("type", "number");
bInput.setAttribute("id", `burstTime ${i}`);
processDiv.appendChild(pLabel);
processDiv.appendChild(pInput);
burstDiv.appendChild(bLabel);
burstDiv.appendChild(bInput);
console.log(pLabel, pInput, bLabel, bInput);
}
});
<form action="">
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button id="start">Start</button>
</form>
</section>
<br /><br />
<section>
<form action="">
<div id="processDiv">
<label for="process0">P0</label>
<input type="number" name="process" id="process0" />
</div>
<div id="burstDiv">
<label for="burstTime0">Burst Time</label>
<input type="number" name="burst time" id="burstTime0" />
</div>
<button id="excute">Execute</button>
</form>
Remove action="" and set type attribute to button if nothing is submitted. The behaviour you describe is due to the form being submitted.
Do like this and you can see you console log for other errors:
<form>
<div>
<label for="numberOfProcesses">Enter Number Of Processes</label>
<input type="number" name="Number Of Processes" id="numberOfProcesses" value="5" />
</div>
<br />
<div>
<label for="timeQuantum">Enter Time Quantum</label>
<input type="number" name="time quantum" value="5" id="timeQuantum" />
</div>
<button type="button" id="start">Start</button>
</form>

How do I assign value of the clicked button

I have the following on jsfiddle. What I need to accomplish is when I click on a button the respective value is inserted in the blank.
https://jsfiddle.net/aminbaig/jefee77L/
Here is the Code:
HTML:
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change()" />
<input type="submit" id="byBtn1" value="Truck" onclick="change()" />
<input type="submit" id="byBtn2" value="Trash" onclick="change()" />
Javascript:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
You can do like this
JS
get the value of the button from the function parameter
function change(value) {
var title = document.getElementById('title');
title.innerHTML = value;
}
HTML
change button type='submit' to type='button', Also pass the value as the function parameter
<input type="button" id="myTextField" value="something" onclick="change(this.value)" />
<input type="button" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="button" id="byBtn2" value="Trash" onclick="change(this.value)" />
DEMO
use like this onclick="change(this.value)" .send the value of the input via click function
function change(val) {
if (val.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = val;
}
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change(this.value)" />
<input type="submit" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="submit" id="byBtn2" value="Trash" onclick="change(this.value)" />

Toggle sub-category divs based on radio button selection

I used the top answer to this question to build a form that feeds into a sheet along with file upload. Now I've hit another wall.
I have categories, and sub-categories. I'd like the sub-categories to only show up IF their parent category has been selected. I just can't figure out A) where I need to put the code (on our website it's right in with the HTML), I've tried putting it in the HTML file and the Code.gs file, or B) if the code I'm using is even right.
Here's the form - the "Co-Op Category" is the parent categories, I have hidden divs for each category that would hold the 'child categories'
HTML:
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name: <input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br>
Other: <input type="text" name="split" /><br />
Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit"
onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
Code.gs:
var submissionSSKey = '1zzRQwgXb0EN-gkCtpMHvMTGyhqrx1idXFXmvhj4MLsk';
var folderId = "0B2bXWWj3Z_tzTnNOSFRuVFk2bnc";
function doGet(e) {
var template = HtmlService.createTemplateFromFile('Form.html');
template.action = ScriptApp.getService().getUrl();
return template.evaluate();
}
function processForm(theForm) {
var fileBlob = theForm.myFile;
var folder = DriveApp.getFolderById(folderId);
var doc = folder.createFile(fileBlob);
// Fill in response template
var template = HtmlService.createTemplateFromFile('Thanks.html');
var name = template.name = theForm.name;
var amount = template.amount = theForm.amount;
var split = template.split = theForm.split;
var reason = template.reason = theForm.split;
var brand = template.brand = theForm.brand;
var category = template.category = theForm.category;
var message = template.message = theForm.message;
var email = template.email = theForm.email;
var fileUrl = template.fileUrl = doc.getUrl();
// Record submission in spreadsheet
var sheet = SpreadsheetApp.openById(submissionSSKey).getSheets()[0];
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 9).setValues([[name,amount,split,reason,category,brand,message,email,fileUrl]]);
// Return HTML text for display in page.
return template.evaluate().getContent();
}
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
This bit specifically is where I'm having trouble:
//Toggle Secondary Categories
function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="dealer"){
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if($(this).attr("id")=="online"){
$(".box").not(".online").hide();
$(".online").show();
}
if($(this).attr("id")=="advertising"){
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if($(this).attr("id")=="pricing"){
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if($(this).attr("id")=="correspondence"){
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if($(this).attr("id")=="meetings"){
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if($(this).attr("id")=="other"){
$(".box").not(".other").hide();
$(".other").show();
}
});
};
The unexpected token is due to the function(){ line, which is invalid syntax for the jQuery document ready function. You should have:
$(function(){
$('input[type="radio"]').click(function(){
...
});
});
With that fixed, your next error will be:
Uncaught ReferenceError: $ is not defined
That's because you haven't included jQuery, which is what the $ symbol is referring to in statements like $(this). You'll want to read this for more tips about using jQuery in Google Apps Script. The short story, though: You need to add the following, adjusted for whatever version of jQuery you intend to use:
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
Updated Form.html, which shows the appropriate <div> as you intended. It also includes the recommended doctype, html, head and body tags:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// Javascript function called by "submit" button handler,
// to show results.
function updateOutput(resultHtml) {
toggle_visibility('inProgress');
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = resultHtml;
}
// From blog.movalog.com/a/javascript-toggle-visibility/
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
//Toggle Secondary Categories
$(function() {
$('input[type="radio"]').click(function() {
if ($(this).attr("id") == "dealer") {
$(".box").not(".dealer").hide();
$(".dealer").show();
}
if ($(this).attr("id") == "online") {
$(".box").not(".online").hide();
$(".online").show();
}
if ($(this).attr("id") == "advertising") {
$(".box").not(".advertising").hide();
$(".advertising").show();
}
if ($(this).attr("id") == "pricing") {
$(".box").not(".pricing").hide();
$(".pricing").show();
}
if ($(this).attr("id") == "correspondence") {
$(".box").not(".correspondence").hide();
$(".correspondence").show();
}
if ($(this).attr("id") == "meetings") {
$(".box").not(".meetings").hide();
$(".meetings").show();
}
if ($(this).attr("id") == "other") {
$(".box").not(".other").hide();
$(".other").show();
}
});
});
</script>
<div id="formDiv">
<!-- Form div will be hidden after form submission -->
<form id="myForm">
Name:
<input name="name" type="text" /><br/>
Co-Op Amount: <input name="amount" type="text" /><br/>
Co-Op Split:<br />
<input type="radio" name="split" value="100%">100%<br>
<input type="radio" name="split" value="50/50">50/50<br>
<input type="radio" name="split" value="75/25">75/25<br> Other: <input type="text" name="split" /><br /> Reason for Co-Op: <input name="reason" type="text" cols="20" rows="5" /><br />
Brand:
<select name="brand">
<option>Select Option</option>
<option>Bluebird</option>
<option>Brown</option>
<option>Ferris</option>
<option>Giant Vac</option>
<option>Honda</option>
<option>Hurricane</option>
<option>Little Wonder</option>
<option>RedMax</option>
<option>SCAG</option>
<option>Snapper Pro</option>
<option>Sno-Way</option>
<option>SnowEx</option>
<option>Wright</option>
<option>Ybravo</option>
</select><br/>
Co-Op Category:<br />
<input type="radio" name="category" id="dealer" value="Dealer Advertising">Dealer Advertising<br />
<input type="radio" name="category" id="online" value="Digital/Online Marketing">Digital/Online Advertising<br />
<input type="radio" name="category" id="meetings" value="Meetings and Schools">Meetings and Schools<br />
<input type="radio" name="category" id="advertising" value="PACE Advertising">PACE Advertising<br />
<input type="radio" name="category" id="pricing" value="Program Pricing Promotions">Program Pricing Promotions<br />
<input type="radio" name="category" id="correspondence" value="PACE-to-Dealer Correspondence">PACE-to-Dealer Correspondence<br />
Other: <input type="text" id="other" name="category" /><br />
<div class="dealer box" style="display: none;">DEALER</div>
<div class="online box" style="display: none;">ONLINE</div>
<div class="meetings box" style="display: none;">MEETINGS</div>
<div class="advertising box" style="display: none;">ADVERTISING</div>
<div class="pricing box" style="display: none;">PRICING</div>
<div class="correspondence box" style="display: none;">CORRESPONDENCE</div>
Email: <input name="email" type="text" /><br/>
Message: <textarea name="message" style="margin: 2px; height: 148px; width: 354px;"></textarea><br/>
School Schedule (Image Files Only): <input name="myFile" type="file" /><br/>
<input type="button" value="Submit" onclick="toggle_visibility('formDiv'); toggle_visibility('inProgress');
google.script.run
.withSuccessHandler(updateOutput)
.processForm(this.parentNode)" />
</form>
</div>
<div id="inProgress" style="display: none;">
<!-- Progress starts hidden, but will be shown after form submission. -->
Uploading. Please wait...
</div>
<div id="output">
<!-- Blank div will be filled with "Thanks.html" after form submission. -->
</div>
</body>
</html>

when the file upload (multiple) complete, the checkbox will auto check

I'm doing a form that after the user upload the file, the checkbox will auto check, so that the user will know that their file had been uploaded.
In the form, there will have few "file upload input" and one "multiple file upload input", each of it will have a checkbox beside that will automatically checked after the file had been uploaded.
here is my code for file upload
<div><input type="checkbox" id="application" value="application" name="application"/><label for="application"><span></span></label>
</div>
<div>
<div>Application Form</div>
<div>
<input id="filename1" type="text"/>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn1" type="file" class="upload" name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
</div>
<div><input type="checkbox" id="application2" value="application2" name="application2"/><label for="application2"><span></span></label>
</div>
<div>
<div>Application Form2</div>
<div>
<input id="filename2" type="text"/>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn2" type="file" class="upload" name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
</div>
Script
document.getElementById('uploadBtn1').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename1').value = filename;
}
here is the fiddle
http://fiddle.jshell.net/kpxyb74h/
here is the code for multiple file
<div><input type="checkbox" id="payment" value="payment" name="payment" /><label for="payment"><span></span></label>
</div>
<div>
<div>Payment</div>
<div>
<div id="upload_prev"></div>
<div class="fileUpload btn btn-primary">
<span>Add</span>
<input id="uploadBtn" type="file" class="upload" multiple name="browsefile" file-accept="pdf, doc, docx, jpg, jpeg, png"/>
</div>
</div>
script
$(document).on('click','.close',function(){
$(this).parents('span').remove();
})
document.getElementById('uploadBtn').onchange = uploadOnChange;
function uploadOnChange() {
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>'+'<div class="filenameupload">'+files[i].name+'</div>'+'<p class="close" >X</p></span>');
}
document.getElementById('filename').value = filename;
}
here is the fiddle for multiple file
http://fiddle.jshell.net/37zjr70k/
I have to separate the script because it unable to function at the same time.
$(document).ready(function () {
$("#uploadBtn1").on("change", function () {
$("#application").attr('checked','checked');
});
$("#uploadBtn2").on("change", function () {
$("#application2").attr('checked','checked');
});
});
You can do the same for multiple uploads!

jQuery Getting uploaded image's name

//Picture upload
$(function() {
$(":file").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>
I need to take the id of the input (#file) and assign it to the hidden input with id (#photo_name) using the picture upload js on top.
I need to take the id of (<input type="file" name="file" id="file" />) and assign it to the id of (<input type="hidden" id="photo_name" name="photo_name">).
I already have the JS that I posted before... I need to use it to do the assigning of id.
I already have the id of the input file though the JS... (this.file[0]) already gives me the name of the uploaded files... now what I need is take this name and assign it to the id of the hidden input.
I need the value of photo_name in my java code below:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String currentRoomTypeIdStr = request.getParameter("current_roomtype_id");
Integer currentRoomTypeId = Integer.valueOf(currentRoomTypeIdStr);
String photoName = request.getParameter("photo_name");
if (!Objects.equals(currentRoomTypeId, null) || !Objects.equals(roomtypeIdToRemove, null)) {
try {
mUserTransaction.begin();
if (currentRoomTypeId == 0) { // Add mode
ChambreTypeEntity typeChambreEntity = new ChambreTypeEntity();
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
else { // Modification mode
Query query = mEntityManager.createQuery("FROM ChambreTypeEntity WHERE id=:pId")
.setParameter("pId", currentRoomTypeId);
List<ChambreTypeEntity> typeChambreEntityList = query.getResultList();
if (!typeChambreEntityList.isEmpty()) {
ChambreTypeEntity typeChambreEntity = typeChambreEntityList.get(0);
typeChambreEntity.setLibelle(inputTypeRoom);
typeChambreEntity.setCode(inputCodeRoom);
typeChambreEntity.setDescription(inputDescriptionRoom);
typeChambreEntity.setNbMinPers(inputMinPerson);
typeChambreEntity.setNbMaxPers(inputMaxPerson);
typeChambreEntity.setNbEnfGratuit(inputChild);
mEntityManager.persist(typeChambreEntity);
mEntityManager.persist(chambreTypeTarifTypeEntity);
ChambrePhotoEntity chambrePhotoEntity = new ChambrePhotoEntity();
chambrePhotoEntity.setNomPhoto(photoName);
chambrePhotoEntity.setTypeChambre(currentRoomTypeId);
mEntityManager.persist(chambrePhotoEntity);
}
}
mUserTransaction.commit();
}
But right now the value of photo_name is "". I need it to be the value that i chose while doing the picture selection.
Is the following is what you're looking for?
//Picture upload
$(function() {
// This is a better way of selecting the input field
$("input[name^=file]").change(function() {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
// This is what you should do
$('#photo_name').val(this.files[0].name);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form_roomtype" class="form-horizontal" style="padding-top: 57px;" action="roomtype" method="POST" enctype="multipart/form-data">
<input type="hidden" id="current_roomtype_id" name="current_roomtype_id" value="0">
<input type="hidden" id="roomtype_id_to_remove" name="roomtype_id_to_remove" value="0">
<input type="hidden" id="chk_tarif_applicable" name="chk_tarif_applicable" value="0">
<input type="hidden" id="photo_name" name="photo_name">
<div>
<span style="font-size: 16.85px; font-family: Arial, Helvetica, sans-serif; color: #757575;">ROOM PICTURE</span>
<br />
<br />
<input type="file" name="file" id="file" />
<br/>
<img id="myImg" src="<%=request.getContextPath()%>/images/insert_images.png" alt="room image" height="175" width="285" onclick="file" />
<br />Destination:
<input type="text" value="C:\Project\Booking_Engine\Java\booking\src\main\webapp\data" name="destination" />
</br>
<br />
<input type="submit" value="Upload" name="upload" id="upload" />
</div>
</form>

Categories

Resources