Get file possibly to string on form submit - javascript

So I'm trying to get a file on submit but i got this code snippet that gets it onchange. Truthfully i do not really understand the first line and how it transitions BUT basically i want to turn it to a function i can call when i click submit and without having the eventlistener there as sometimes it does not work unless called on the html form.
const fileSelector = document.querySelector('#a_pic');
fileSelector.addEventListener('change', (event) => {
const fileList = event.target.files;
file = fileList[0];
pic_url = URL.createObjectURL(file);
alert(file)
document.querySelector('#secondcheck').innerHTML = '<img src = "' + pic_url + '">';
a_pic = file;
});
Html code:
<form>
<input class= "form-control" type = "file" name= "a_pic" id= "a_pic" accept= "image/*">
<button type="button" value = "submit" name = "submit" id="submit" onclick = "whatever_the_newfunction_may_be()">submit</button>
Please any explanation is appreciated as i am relatively new green in javascript.

This works fine. There's a variety of ways to handle a form submission, but here's one where you don't use the form's submit event but instead just a button's click event.
const fileSelector = document.querySelector('#a_pic');
let picBlobUrl;
fileSelector.addEventListener('input', (event) => {
const fileList = event.target.files;
file = fileList[0];
picBlobUrl = URL.createObjectURL(file);
});
function submitClicked() {
document.querySelector('#secondcheck').innerHTML = '<img src="' + picBlobUrl + '">';
}
<div>
<input class="form-control" type="file" name="a_pic" id="a_pic">
<button onclick="submitClicked()">submit</button>
</div>
<div id="secondcheck"></div>

Related

how submit dynamic forms

I have the following problem that I cannot solve
is a form of this type
in HTML
<button (click)="addform()">agregar formulario</button>
<div class="conten-form">
<div class="MyForm">
<label>Nombre</label>
<input type="text" class="name">
<label>descripcion</label>
<input type="text" class="description">
<label>Foto</label>
<div class="img-cont">
<div class="img">
<img src="{{img}}">
</div>
<div class="addimg">
<input type="file" (change)="createimg($event)">
</div>
</div>
</div>
<div class="AddForm"></div>
<input type="buttom" value="enviar" (click)="enviarform()">
</div>
in TS
img : any; //to show
imgfile : any; //to send it through the form
constructor(...){...}
addform(){
let addform = document.querySelectorAll('.AddForm');
let myform = document.querySelectorAll('.MyForm');
let cloneform = myform.cloneNode(true);
addform.appendChild(cloneform);
}
createimg(event){
this.imgfile = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.imgfile);
reader.onload = () => {
this.img = reader.result;
};
}
enviarform(event){
let nombre = document.querySelectorAll(".name");
let description = document.querySelectorAll(".description");
let formdata = new FormData;
//add all inputs class name
for (let i = 0; i < nombre .length; i++) {
let stringname = (nombre.[i] as HTMLTextAreaElement).value;
formdata.append('name',stringname);
}
//add all inputs class description
for (let i = 0; i < description.length; i++) {
let stringdescription = (description.[i] as HTMLTextAreaElement).value;
formdata.append('description',stringdescription );
}
//send the form
}
As you will see, I can add more forms with the add button, cloning the first one, the part of the text inputs I have solved to add as many as I want, but in the part of the inputs for the image I have no idea how to do it, the operation is that after attaching an image to the input, I get a preview image of what I am going to attach in the div.class = img, this makes it only work in the first form, and it no longer works in the forms that I add dynamically, as it could fix this issue? taking into account that I have to send it through the formdata in a single shipment, I thank you in advance.
you should not use
let addform = document.querySelectorAll('.AddForm');
let myform = document.querySelectorAll('.MyForm');
let cloneform = myform.cloneNode(true);
at all. to add forms. instead you should create a separate component for each form.
check my question earlier on stackoverflow to get what I mean.
more specifically check the answer stackblitz.

Global array remains empty

I am trying to update my global array, but it remains null after I submit a text value(.name) through a submit button.
Please tell me how I can keep track of text values in my global array. Thank you.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#form1").onsubmit = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});
When the form is submitted, a new page is loaded. It loads the URL in the action property of the form. So, your variable goes away.
If you don't want that to happen, prevent the form from being submitted with preventDefault.
For example ...
const name_list = [];
window.addEventListener('DOMContentLoaded', (e) => {
const names = document.querySelector(`.names`);
const add_button = document.querySelector(`.names--add_button`);
names.addEventListener('submit', e => e.preventDefault());
add_button.addEventListener('click', (e) => {
const name = document.querySelector(`.names--name`);
const collected = document.querySelector(`.names--collected`);
name_list.push(name.value);
collected.innerHTML += `<li>${name.value}</li>`;
name.value = ``;
name.focus();
});
});
body { background: snow; }
<form class="names" action="#" method="post">
<label>Name: <input type="text" name="name" class="names--name"></label>
<button class="names--add_button">Add To List</button>
<div>Names Collected:</div>
<ul class="names--collected">
</ul>
</form>
I am see at the moment it's working perfect. but you want add value every time when you click the button. so just changed the type of your
<button type="submit"> to <button type="button">
because when you click on submit page automatically reload in html, an the 2nd thing you need to change your event from onsubmit to onclick and your button to it instead of your form.
var display_name = [];
document.addEventListener('DOMContentLoaded', () =>{
document.querySelector("#button1").onclick = () => {
let name = document.querySelector(".name").value;
display_name.push(name);
};
});

How to update image src attribute using user input value

I am building a simple photo editor app using imgix, and I want the image src attribute to be updated when a user input fields receive values. Is there a way to append my new parameters onto the end of the src url?
I have been able to use template literals to create a new url, however I haven't been able to figure out how or if I can update the image src as the user types. Or if the only way to do this would be submitting the changes and show the new image on page reload. I have tried reassigning image.src to the new url, but that hasn't worked.
HTML:
<form id="form" class="input-container">
<input type="text" placeholder="Enter Text" id="title"/>
<input type="text" placeholder="Enter Hexcode Color" id="overlay" />
<input type="submit" value="Apply Changes" id="edit-submit">
</form>
JavaScript:
let form = document.getElementById("form");
let titleInput = document.getElementById("title");
let encodedTitle = encodeURI(titleInput);
let overlayColor = document.getElementById("overlay");
let image = document.getElementById("image");
let timeout = null;
form.onkeyup = function(e) {
let encodedTitle = "&txt=" + encodeURI(titleInput.value);
let newColor = "&blend=" + overlayColor.value;
let url = new URL(`${image.src}`);
url = `${url}${encodedTitle}${newColor}`;
console.log(url);
document.getElementById("url-result").value = url;
image.src = url;
};
I am able to grab the values but I haven't figured out what I'm needing to do to apply it to the img src url.
Your code changes the URL of the image, but the URL gets longer and longer with each keyup.
Look at this snippet - maybe it helps.
let form = document.getElementById("form");
let titleInput = document.getElementById("title");
let encodedTitle = encodeURI(titleInput);
let overlayColor = document.getElementById("overlay");
let image = document.getElementById("image");
let timeout = null;
// URL base for your image - so it doesn't get longer-and-longer
// with each keyup
let baseURL = image.src
// just a display element, so you can see the URL created
let display = document.getElementById('new-url')
form.onkeyup = function(e) {
const newURL = `${baseURL}&txt=${encodeURI(titleInput.value)}&blend=${overlayColor.value}`
document.getElementById("url-result").value = newURL;
image.src = newURL
display.textContent = newURL
};
img {
width: 100px;
height: 100px;
}
<img id="image" src=""><br />
<label for="url-result">URL Result:
<input type="text" id="url-result">
</label>
<div>Display new URL: <span id="new-url"></span></div>
<form id="form" class="input-container">
<input type="text" placeholder="Enter Text" id="title" />
<input type="text" placeholder="Enter Hexcode Color" id="overlay" />
<input type="submit" value="Apply Changes" id="edit-submit">
</form>

How to clear one input type file in javascript from multiple file uploads

I have the 2 file upload field and each one have the 'Clear' Button.
When I upload the files and click one of the ''Clear' Button then all the
file upload are clear. but I need to clear one file.
Pleas see my code
<input type="file" id="control1"/>
<button id="clear1">Clear</button>
<input type="file" id="control2"/>
<button id="clear2">Clear</button>
var control = $("#control1");
$("#clear1").on("click", function () {
control1.replaceWith( control1 = control1.clone( true ) );
});
var control2 = $("#control2");
$("#clear2").on("click", function () {
control2.replaceWith( control2 = control2.clone( true ) );
});
Try this:
<script type="text/javascript">
function clear2() {
var fileUpload = document.getElementById("<%=control2.ClientID %>");
var id = fileUpload.id;
var name = fileUpload.name;
//Create a new FileUpload element.
var newFileUpload = document.createElement("INPUT");
newFileUpload.type = "FILE";
//Append it next to the original FileUpload.
fileUpload.parentNode.insertBefore(newFileUpload, fileUpload.nextSibling);
//Remove the original FileUpload.
fileUpload.parentNode.removeChild(fileUpload);
//Set the Id and Name to the new FileUpload.
newFileUpload.id = id;
newFileUpload.name = name;
return false;
}
function clear1() {
var fileUpload = document.getElementById("<%=control1.ClientID %>");
var id = fileUpload.id;
var name = fileUpload.name;
//Create a new FileUpload element.
var newFileUpload = document.createElement("INPUT");
newFileUpload.type = "FILE";
//Append it next to the original FileUpload.
fileUpload.parentNode.insertBefore(newFileUpload, fileUpload.nextSibling);
//Remove the original FileUpload.
fileUpload.parentNode.removeChild(fileUpload);
//Set the Id and Name to the new FileUpload.
newFileUpload.id = id;
newFileUpload.name = name;
return false;
}
</script>
<input type="file" id="control1"/>
<input id="Button1" type="button" value="clickme" onclick="clear1();" />
<input type="file" id="control2"/>
<input id="clickMe" type="button" value="clickme" onclick="clear2();" />

ajaxForm is sending empty POST when submit from dynamically built form

Submitting a file with ajaxSubmit() works fine when the form is hard-coded. But the data received by the server is empty when the form is created dynamically.
This version works
HTML
<form id='file_upload_form' method="POST" enctype="multipart/form-data" action="/upload">
<input type="file" id='myfile' name="myfile" />
<br/>
<input type="submit" />
</form>
<div id='status'> </div>
JavaScript
jQuery(document).ready(function() {
jQuery("#file_upload_form").on("submit", function(e) {
e.preventDefault();
jQuery(this).ajaxSubmit({
target: '#status'
});
});
});
Debuggin in .on("submit"... , jQuery(this).formSerialize() yields "myfile=%5Bobject+File%5D"
But this version using a dynamically created form sends empty data
HTML
<div id='parent_elem_div'> </div>
<div id='status'> </div>
JavaScript
jQuery(document).ready(function() {
var parent_elem = jQuery('#parent_elem_div');
var new_form_elem = build_form();
parent_elem.append(new_form_elem);
});
jQuery(document).ready(function() {
jQuery("#file_upload_form").on("submit", function(e) {
e.preventDefault();
jQuery(this).ajaxSubmit({
target: '#status'
});
});
});
But here, debuggin in .on("submit"... , jQuery(this).formSerialize() yields "".
This function builds the form...
//
function build_form (){
var new_inner_div_elem = document.createElement('div');
new_inner_div_elem.id = 'parent_elem_div';
var upload_form = document.createElement('form');
upload_form.id = 'file_upload_form';
upload_form.action = '/upload';
upload_form.method = 'POST';
upload_form.enctype="multipart/form-data";
var file_input = document.createElement('input');
file_input.type = 'file';
file_input.id = 'file_upload_input';
var file_upload_submit = document.createElement('input');
file_upload_submit.type = 'submit';
upload_form.appendChild(file_input);
upload_form.appendChild(file_upload_submit);
new_inner_div_elem.appendChild(upload_form);
return new_inner_div_elem;
}
Aha! Here it go, in your code:
var file_input = document.createElement('input');
file_input.type = 'file';
file_input.id = 'file_upload_input';
This is missing:
file_input.attr('name', 'myfile');
This is the only part that your HTML form has, and dynamical doesn't, so I guess that's the trick
If an HTML doesn't have a name it won't be passed to the
querystring or the POST data - there will be no way to retrieve it
from PHP
This is from here - stackoverflow

Categories