I can't find any solution for this anywhere. I would like to allow user to see calendar when clicking on my input, but when user will try to change the value, it shouldn't change (or immediately change back for value, what was at the beggining).
Readonly attribute removes calendar, so I was trying to do it different ways like use onchange/onclick functions to restore my value after event, but the value was changing anyway.
So for now my input looks like this:
<input class='test' type='date' value='2020-06-04' onkeydown='return false' >
So at least user can't change value of my input using keyboard. Could you help me?
You might try to set a time limit
<html>
<body>
<input type="date" value="2020-06-04">
<input type="date" value="2020-06-04" min="2020-06-04" max="2020-06-04">
</body>
</html>
If I understood correctly, this is what you want.
HTML
<input class='test' type='date' value='2020-06-04' />
JavaScript
const date = "2020-06-04";
const input = document.querySelector('.test');
input.onkeydown = function(e) {
return false;
}
input.onchange = function(e) {
this.value = date;
}
Check out this JSFiddle
EDIT
function preventInputChange(input, staticValue) {
input.onchange = function(e) {
this.value = staticValue;
}
}
This was discussed a lot, but all of these solutions not work:
$("#getFile").val('');
Nor this:
document.getElementById("getFile").value = "";
When console.log after using one of this - it prints the value of last file attached.
Also cloning not works, although remove the input value.
I want to trigger the event "change" when the user uses the same file after removing. The problem is thatthe value of the input is the last file uploaded.
why not just track the value with another variable and do an if statement? Like var lastUpload = document.getElementById("getFile").value;
then
addEventListener("change", function() {
if(lastUpload === document.getElementById("getFile").value) {
...
}
);
I think this is only possible if you can reset the form as well, see below:
<form action="#" id="form">
<label>Choose File: </label> <input type="file" name="getFile" id="getFile" /><br />
<button type="button" onClick="removeFileName()">Clear File</button>
</form>
And JS:
function removeFileName(){
form.reset();
var field = document.getElementById("getFile");
console.log(field.value);
}
I am trying a very simple example. I have a file field and text field. Once the file selected, its value need to be updated in the text box.
My code looks like below
<input id="selectedFiles" type="text" ng-model="selectedFiles" placeholder="No file(s) chosen">
<input id="file" type="file" name="file" multiple onchange="angular.element(this).scope().fileChange()">
I know ng-change does not work for the input-type file, so I have used onchange method like above
On the javascript side my code looks like
$scope.selectedFiles = "";
$scope.fileChange = function () {
file = document.getElementById("file");
$scope.selectedFiles = file.value;
}
I am updating the value model value in onchange, but in UI it is not reflecting although input is binded through slectedFiles variable.
JSFIDDLE LINK
What should I do so the value reflects in the UI?
You have to wrap the body of your fileChange function with a call to $scope.$apply. Angular will otherwise not test whether the model has changed.
$scope.selectedFiles = "";
$scope.fileChange = function () {
$scope.$apply(function() {
file = document.getElementById("file");
$scope.selectedFiles = file.value;
});
}
I was using this code fine on bothe IE9 and Firefox but now it works only on Firefox and it just doesn't execute Java validation part on IE9. Any idea what I may need to do to make it work on both type of browserss? Thanks
<?php
if(isset($_POST['submit'])) {
$first_name=$_POST['fname'];
echo 'Entered First Name = '.$first_name;
}
?>
<html>
<form method="post" enctype="multipart/form-data" action="">
<label for="fname"> First Name: </label> <input type="text" name="fname" /> <br /><br />
<label for="file"> Select File: </label> <input type="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
</script>
</html>
The fact that the files array does not exist is not due to a code error. Internet Explorer 9 and below do not support the HTML5 File API, so you will have to use a workaround such as uploading with a Java applet or Adobe Flash.
Combined with what Alex W said, your code also needs some tweaking. getElementsByName requires a name attribute from where you are trying to select. It returns a NodeList of elements with the name given in the function. .
Change your input to have a name attribute, then you won't even need that function:
<input type="file" name="file" />
id works just fine. See below.
I stand corrected by my own research. All the above is true about getElementsByName, however to retrieve the File object, you have to call it from an array returned by selecting a file input form type. As such, document.getElementById('file').files[0] should work. So will the method below:
window.onload = (function () {
document.forms[0].addEventListener('submit', function (evt) {
//this works
var file = document.forms[0].file.files[0];
//as does this
file = document.getElementById('file').files[0];
if (file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
});
jsFiddle
Even after all is said and done, it still will not work in browsers that do not support the HTML5 File API (looking at you IE).
Edit
Whoa, whoa, whoa hold the reigns? I just read that the id attribute was slated to replace the name attribute once IE6 gets nuked. Apparently this is old news1 2 3.
So I did some testing and it turns out id works just fine when calling the element the same way:
var file = document.forms[0].file;
Prove it? Ok
Looks like you have a script error.
The files property does not seems to be supported in IE9
document.forms[0].addEventListener('submit', function( evt ) {
var f = document.getElementById('file');
var file = f.files ? f.files[0] : f;
if(file && file.size < 18000) {
//Submit form
alert('Size is valid');
} else {
alert('pic too big');
evt.preventDefault();
}
}, false);
Demo: Fiddle
I have a hidden file input element. Is it possible to trigger its select file dialog box from a button's click event?
If you're looking to have your own button to upload a file instead of using <input type="file" />, you can do something like:
<input id="myInput" type="file" style="visibility:hidden" />
<input type="button" value="Show Dialog" onclick="$('#myInput').click();" />
Note that I used visibility: hidden, instead of display: none. You cannot call the click event on a non-displayed file input.
Most answers here are lacking a useful information:
Yes, you can programmatically click the input element using jQuery/JavaScript, but only if you do it in an event handler belonging to an event THAT WAS STARTED BY THE USER!
So, for example, nothing will happen if you, the script, programmatically click the button in an ajax callback, but if you put the same line of code in an event handler that was raised by the user, it will work.
P.S. The debugger; keyword disrupts the browse window if it is before the programmatical click ...at least in chrome 33...
Just for the record, there is an alternative solution that does not require javascript. It is a bit of a hack, exploiting the fact that clicking on a label sets the focus on the associated input.
You need a <label> with a proper for attribute (points to the input), optionnaly styled like a button (with bootstrap, use btn btn-default). When the user clicks the label, the dialog opens, example :
<!-- optionnal, to add a bit of style -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<!-- minimal setup -->
<label for="exampleInput" class="btn btn-default">
Click me
</label>
<input type="file" id="exampleInput" style="display: none" />
I'm not sure how browsers handle clicks on type="file" elements (security concerns and all), but this should work:
$('input[type="file"]').click();
I've tested this JSFiddle in Chrome, Firefox and Opera and they all show the file browse dialog.
Nowadays a hybrid solution like this can have the best experience,
let fileHandle;
async function fileOpen() {
[fileHandle] = await window.showOpenFilePicker();
const file = await fileHandle.getFile();
console.log(await file.text());
}
// The advantage of this is fileHandle can be used to save to
// the opened file itself later, read more on this in https://web.dev/file-system-access/
// in April 2021, window.showOpenFilePicker still not support in Safari
// so one should have this around also
function legacyFileOpen() {
var input = document.createElement('input');
input.type = 'file';
input.onchange = function () {
input.files[0].arrayBuffer().then(function (arrayBuffer) {
console.log(new TextDecoder().decode(arrayBuffer));
});
}
input.click();
}
I wrap the input[type=file] in a label tag, then style the label to your liking, and hide the input.
<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
<input type="file">
<span><i class="fa fa-upload"></i></span>
</label>
<style>
.fileLabel input[type="file"] {
position: fixed;
top: -1000px;
}
</style>
Purely CSS Solution.
Natively the only way is by creating an <input type="file"> element and then simulating a click, unfortunately.
There's a tiny plugin (shameless plug) which will take the pain away of having to do this all the time: file-dialog
fileDialog()
.then(file => {
const data = new FormData()
data.append('file', file[0])
data.append('imageName', 'flower')
// Post to server
fetch('/uploadImage', {
method: 'POST',
body: data
})
})
The best solution, works in all browsers.. even on mobile.
<div class="btn" id="s_photo">Upload</div>
<input type="file" name="s_file" id="s_file" style="opacity: 0;">';
<!--jquery-->
<script>
$("#s_photo").click(function() {
$("#s_file").trigger("click");
});
</script>
Hiding the input file type causes problems with browsers, opacity is the best solution because it isn't hiding, just not showing. :)
There is no cross browser way of doing it, for security reasons. What people usually do is overlay the input file over something else and set it's visibility to hidden so it gets triggered on it's own. More info here.
Make sure you are using binding to get component props in REACT
class FileUploader extends Component {
constructor (props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
onChange=(e,props)=>{
const files = e.target.files;
const selectedFile = files[0];
ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
}
handleClick = () => {
this.refs.fileUploader.click();
}
render()
{
return(
<div>
<button type="button" onClick={this.handleClick}>Select File</button>
<input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
</div>)
}
}
browse file programatically
function browseFile(accept) {
const promise = resolvingPromise();
const input = document.createElement('input');
input.type = "file";
input.accept = accept;
input.onchange = function (e) {
const files = e.target.files;
promise.resolve(files);
}
setTimeout(function () {
click(input);
}, 0);
return promise;
}
function click(node) {
try {
node.dispatchEvent(new MouseEvent('click'))
} catch (e) {
const evt = document.createEvent('MouseEvents')
evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null)
node.dispatchEvent(evt);
}
}
Using jQuery you can call click() to simulate a click.
This worked for me:
$('#fileInput').val('');
For those who want the same but are using React
openFileInput = () => {
this.fileInput.click()
}
<a href="#" onClick={this.openFileInput}>
<p>Carregue sua foto de perfil</p>
<img src={img} />
</a>
<input style={{display:'none'}} ref={(input) => { this.fileInput = input; }} type="file"/>
<div id="uploadButton">UPLOAD</div>
<form action="[FILE_HANDLER_URL]" style="display:none">
<input id="myInput" type="file" />
</form>
<script>
const uploadButton = document.getElementById('uploadButton');
const myInput = document.getElementById('myInput');
uploadButton.addEventListener('click', () => {
myInput.click();
});
</script>