I have a form in which I allow files to be loaded using file input. I want to allow users to delete the upload item but I wasn't able to figure it out. Here is what I have tried to do so far:
<form action="insert.php" method="POST" align="right" id="post_form">
<input type="file" id="upload_file" onChange="display()">
<div id="show_button" onClick="remove_pic()"> remove </div><br>
</form>
function remove_pic() {
alert('check');
var file_loaded = document.getElementById("upload_file");
file_loaded = null; // here i try to remove the object
}
Upon running your code through JSFiddle and checking the Chrome dev console, I kept receiving a "Function not defined" error message.
I found that explicitly putting the function you're trying to call directly into the global scope allowed it to be recognized as defined. You'll also want to use a blank string instead of null and append a change to the ".value" property to your "file_loaded" variable.
Instead of
function remove_pic() {
alert('check');
var file_loaded = document.getElementById("upload_file");
file_loaded = null; // here i try to remove the object
}
try
window.remove_pic = function() {
alert('check');
var file_loaded = document.getElementById("upload_file");
file_loaded.value = ""; // here i try to remove the object
};
Example JSFiddle: http://jsfiddle.net/xu6SD/1/
Related
Is there any chance to detect every file selection the user made for an HTML input of type file element?
This was asked many times before, but the usually proposed onchange event doesn't fire if the user select the same file again.
Set the value of the input to null on each onclick event. This will reset the input's value and trigger the onchange event even if the same path is selected.
var input = document.getElementsByTagName('input')[0];
input.onclick = function () {
this.value = null;
};
input.onchange = function () {
console.log(this.value);
};
<input type="file" value="C:\fakepath">
Note: It's normal if your file is prefixed with 'C:\fakepath'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.
Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)
onInputClick = (event) => {
event.target.value = ''
}
<input type="file" onChange={onFileChanged} onClick={onInputClick} />
Using TypeScript
onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
const element = event.target as HTMLInputElement
element.value = ''
}
<form enctype='multipart/form-data'>
<input onchange="alert(this.value); this.value=null; return false;" type='file'>
<br>
<input type='submit' value='Upload'>
</form>
this.value=null; is only necessary for Chrome, Firefox will work fine just with return false;
Here is a FIDDLE
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
handleChange({target}) {
const files = target.files
target.value = ''
}
<input #myInput type="file" id="imgFile" (click)="$event.target.value=null"
(change)="detectUploadedImage($event)" accept="image/*" />
Clearing the value of 0th index of input worked for me. Please try the below code, hope this will work (AngularJs).
scope.onClick = function() {
input[0].value = "";
input.click();
};
Usage of two way binding worked for me if you are working with Angular.
Here is my HMTL
<input type="file" #upload name="upload" [(ngModel)]="inputValue"(change)='fileEvent($event)'/>
and TS..
#ViewChild('upload') uploadBtn: HTMLElement;
fileEvent(e: any){
//file upload part...
this.inputValue = "";
}
The selected answer (using state to set input value null) gave me an error.
I use empty strings instead
const [fileValue, setFileValue] = React.useState("")
<input
onClick={() => {
setFileValue("");
}}
type="file"
value={fileValue}
onChange={handleAddFile}
/>
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
I am creating a script to upload XML-files to a server, where you enter how often specific tags occur in the file. Now I wanted to automate this, so that i check the XML-file befor uploading, so that the previous manually entered fields are filled automaticly.
I just dont get the point how i can get the content of the file befor actually uploading it - i want to use Javascript for the check and auto-fillment.
The upload is completly realized in php.
Someone have an idea for me?
Edit:
var fileInput;
window.onload = function() {
fileInput = document.getElementById('file_input');
};
function getNodes() {
var anzNodes = fileInput.getElementsByTagName("node").length;
return anzNodes;
}
function getEdges() {
var anzEdges = fileInput.getElementsByTagName("edge").length;
return anzEdges;
}
function fillForm() {
document.getElementById("nodes").value = getNodes();
document.getElementById("edges").value = getEdges();
}
So I have a html-form with the ID file_input. I try to grab that file (which is XML) befor uploading, search it for the amount of "node" and "edge" tags, and autofill these information into the html form. This should happen when the file is chosen. Is this better?
Use the FileReader functionality in JavaScript to grab the document before uploading it. Then you can read the text of the file and pre-process it before sending it to the server.
I found the answer and will provide it for completeness.
My Javascript part:
var openFile = function (event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function () {
var anzEdges = (reader.result.match(/<edge/g) || []).length;
var anzNodes = (reader.result.match(/<node/g) || []).length;
document.getElementById("nodes").value = anzNodes;
document.getElementById("edges").value = anzEdges;
};
reader.readAsText(input.files[0]);
};
and the relevant html-code:
<input type="file" onchange="openFile(event)" name="file_upload" size="60"><br>
<input type="number" id="nodes" name="nodes" min="2" readonly><br>
<input type="number" id="edges" name="edges" min="1" readonly>
So I have a HTML form with a keypress event listener recording the charCode of the key pressed and then convert that charCode to a String of the letter related to the key.
Each time a letter is entered to the form, a new entry is created in input_array[].
I have each letter in the alphabet stored as a SVG within JS variables in a different part of my main.js file and I would like to be able to read what letters have been stored in input_array[] and then display the SVG appropriate to that letter on a new page once the form has been submitted.
I've tried using the method below to extract the data from the array, but it fires on the first keypress and therefore I can't get all of the array data to then display the 4 letters. I also feel like there has to be a more efficient way.
var letter_one = input_array[0];
var letter_two = input_array[1];
var letter_three = input_array[2];
Here's a JSFiddle, to show a basic version of what I'm trying to do. If you open the console you will see how input_array[] is being created.
I'm still very new to this language, so any help would be greatly appreciated.
As you suspected, this is much simpler than you're making it :)
When the form is submitted you can just snag the value from the input:
function handleSubmit() {
var val = document.getElementById('user_input').value;
validate(val);
console.log(val);
var letter_one = val[0];
var letter_two = val[1];
var letter_three = val[2];
var letter_four = val[3];
return false; // stops POST for dev
}
https://jsfiddle.net/1htpm6ag/
That being said, if you are actually doing this on a POST then on the page you are POSTing to you'll have to snag this from the POSTed form data, which is entirely different. Are you trying to do this in client side JS or a POST handler?
If I am understanding you correctly is sound like you want to do the following.
On Page 1 user enters text into textfield.
On Submit send that text to page 2.
On Page 2 convert that text into an array of letters to associate with SVG paths to display.
If the above is the case you need a lot less javascript.
Page 1: Should only have your form with your text box and a submit button so the data is submitted to the next page using the GET method.
Page 2: Here is where you will need the Javascript to retrieve that data sent across and process it into your array of letters. I would also filter for non-letter characters as well.
I have created an example form in the code below that submits to itself and then the javascript script tag will pull the variable from the url and process it into an array of letters. In your case you would move the Javascript to page 2.
<script type="text/javascript">
(function(){
function getParamValue(param) {
var urlParamString = location.search.split(param + "=");
if (urlParamString.length <= 1) return "";
else {
var tmp = urlParamString[1].split("&");
return tmp[0];
}
}
function isLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
var user_input = getParamValue('user_input');
var char_array = null;
if(user_input !== ''){
char_array = user_input.split("");
char_array = char_array.filter(isLetter);
for(var i in char_array){
console.log('Char ' + i + ' = ' + char_array[i]);
}
}
})();
</script>
<body>
<form id="user_form" class="" action="?" method="GET">
<input type="text" name="user_input" />
<input type="submit" value="submit">
</form>
</body>
I am trying to make a javascript function that modifies the hidden value of a form depending on what button you click and then send it via post to a page that processes it.
I checked that the value is modified correctly, but when the post is sent the default value is sent.
Any help?
Here the js function:
function citar(key)
{
document.getElementById('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
EDIT: I did this and now it works. jQuery!
function citar(key)
{
$("#ncita").attr("value", key);
$('#form-cita').submit();
}
Your main problem here is that you are using
document.getElementsByName
which returns an array. Therefor the implementation of key is invalid.
if you are using jQuery you might use
$('[name=esta-cita]').each(function() {
$(this).val(key); //this will insert key to all esta-cita named parameters, even if only 1
});
if you only have 1 parameter of this kind so :
$('[name=esta-cita]').val(key);
});
i deeply recommand you to use jQuery jQuery website
in javascript's case i would have recommand you to use
document.getElementById on 'esta-cita' as well.
if you want to insert key to all elements in javascript i would recommand a very efficient way :
document.getElementsByName('esta-cita').forEach(function(entry) {
entry.value = key; //entry indicates a cell in the array
This returns an array of elements, so you'll have to iterate through it like a normal array.
function citar(key)
{
document.getElementsByName('esta-cita').value=key;
document.getElementById('form-cita').submit();
}
Should be:
function citar(key)
{
var derp = document.getElementsByName('esta-cita');
for (var i=0;i<derp.length;i++) {
derp[i].value = key;
}
document.getElementById('form-cita').submit();
}
Or just document.getElementsByName('esta-cita')[0].value=key; if you just want the first one
Try with,
document.getElementsByName('esta-cita')[0].value=key;
you can access to a length property document.getElementsByName('esta-cita').length to know how many elements are matched
Alternatively you can try this
function citar(key)
{
document.forms['form-cita'].esta-cita.value = key;
document.forms['form-cita'].submit();
}
HTML should be like
<form action="putActionHere" method="POST" enctype="multipart/form-data" id="form-cita">
<input type="hidden" name="esta-cita" id="esta-cita" value="yourval">
...
<input type="submit" value="Submit" onClick="citar('keystring');" />
</form>
I have a form thats displayed in a modal box now I want to be able to use the same modal box for 2 different pages where they do slightly different things. Is there a way I can set an event or something for the forms submit button to set which javascript function it calls.
I want to do this from within javascript without changing my form code.
Whats the best way to do this?
Can I set a function to a variable and have it called by my button code?
ie:
var buttonFunction;
//Set the button function on load
function MyButtonFuntion() {
buttonFunction();
}
you could do it like this:
var buttonFunction;
if(someCondition){
buttonFunction = function(){
alert("some action");
};
}else{
buttonFunction = function(){
alert("other action");
};
}
function MyButtonFuntion() {
buttonFunction();
}
You may declare a variable with the function name to be called on submit. The following code is an example. Declaring the function to call in a variable functionToCall inside the form will always work here.
<script type="text/javascript">
function callMyFunction(formName) {
var formObj = eval("document." + formName);
if(formObj != null) {
var functionToCall = eval(formObj.functionToCall.value);
if(functionToCall) {
functionToCall();
}
}
}
</script>
<form method="post" name="form1">
<input type="hidden" name="functionToCall" value="form1Function"/>
<input type="button" onclick="callMyFunction('form1')"/>
</form>