How can I change the label name when file is selected? - javascript

HTML is given below-
<input type="file" class="custom-file-input" accept="image/*" onchange="loadFile(event)" id="customFile">
<label class="custom-file-label" id="change" for="customFile">Choose File</label><br><br>
<img width="150px" id="output" src="#"/>
Script is given below-
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
My code is able to show the image selected but I also Want to Change The Label text to selected image name

The logic to change the label text can be written on the change event. Check the following event snippet,
document.getElementById('customFile').onchange = function() {
// code to change the label text
var fullName = getFileName(document.getElementById('customFile').value);
document.getElementById("change").innerHTML= fullName;
};
var getFileName = function(fullPath) {
if (!fullPath) return null;
var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
var filename = fullPath.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
return filename.substring(1);
}
return null;
}
For more input on getting the file name check https://stackoverflow.com/a/857662/17542117

Var name = document.getElementById("customFile").value;
Use
document.getElementById("Change").innerHTML = name
Please correct the spelling.

Related

How do I get the Onkey Function to copy the value of a input textfield to the other 3 textfields

This is the Java Script I'm using. I can enter in the proceduredate and it copies to proceduredate2 but not 3 and 4--Same with Procedure
function copyTextAreaValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
console.log('no dest element ' + destIds[i]);
}
}
}
}
Link to JSFiddle with full code
Your question id not clear to me. However, all I understood is you want to copy text from your current text input to other three text input. If that is true, then you can have your solution here. Please, checkout the snippet below.
let el = document.getElementById('field_1');
function copyTextValue() {
let elVal = el.value;
document.getElementById("field_2").value = elVal;
document.getElementById("field_3").value = elVal;
document.getElementById("field_4").value = elVal;
}
copyTextValue();
el.oninput = copyTextValue;
el.onchange = copyTextValue;
Today's Date: <input id="field_1" value=""/><br/>
Procedure Date: <input id="field_2" value=""/> <br/>
Date of Procedure: <input id="field_3" value=""/> <br/>
Surgery Date: <input id="field_4" value=""/> <br/>
function copyTextfieldValue(id, ids) {
// get source element
var sourceElement = document.getElementById(id);
if(sourceElement) {
// copy to destination elements
var destIds = ids.split(',');
for(i=0; i<destIds.length; i++) {
var destEle = document.getElementById(destIds[i]);
if(destEle) {
destEle.value = sourceElement.value;
} else {
//console.log('no dest element ' + destIds[i]);
}
}
}
}
<input id="t1">
<input id="t2">
<input id="t3">
<input id="t4">
<input type="button" value='copy' onclick="copyTextfieldValue('t1','t2,t3,t4');">
Your code seems to work fine. See the snippet.

adding events to dynamically created elements using JS or Jquery

I am creating a div block dynamically. In the div, i am having text fields and one file field and one hyperlink. on clicking the hyperlink, the div tag will be removed from its parent. coming to the file field, i want to add onchange event to the file, which is not working for me. Please check my code and correct me if i am wrong?
this is my code:
<div id="incdiv" class="incdiv" name="incdiv">
<div id="increpeatdiv">
<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>
</div>
add one more Incident
</div>
<script>
function repeat(){
var p=document.getElementById('incdiv')
var element = document.createElement('div');
element.id='increpeatdiv'+p.children.length;
element.innerHTML='<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>'+
'Delete Incident;';
p.appendChild(element);
}
function delete(a){
var p=document.getElementById(a)
var h=document.getElementById('incdiv');
h.removeChild(p);
}
function filelogValidation(input){
var fileInput = document.getElementById(input);
var filePath = fileInput.value;
var allowedExtensions =
/(\.txt)$/i;
if (!allowedExtensions.exec(filePath)) {
alert('Invalid file type. Please Upload .txt format');
fileInput.value = '';
return false;
}
else return true;}
}
I am guessing the problem to be of id "ifile". But I dont know how to solve it. Can somebody help me?
Check this
<div id="incdiv" class="incdiv" name="incdiv">
<div id="increpeatdiv">
<input type="file" class="" id="ifile" name="ifile" onchange="return filelogValidation('ifile')"/>
</div>
add one more Incident
</div>
<script>
var i = 1; //index for doing identity to ifiles like ifile_1, ifile_2 ...
function repeat(){
var p=document.getElementById('incdiv')
var element = document.createElement('div');
element.id='increpeatdiv_'+i;
element.innerHTML="<input type=\"file\" class=\"\" id=\"ifile_"+i+"\" name=\"ifile\" onchange=\"return filelogValidation(this.id)\"/>"+
"Delete Incident;";
p.appendChild(element);
i++;
}
function delete_(a){
var p=document.getElementById(a)
var h=document.getElementById('incdiv');
h.removeChild(p);
}
function filelogValidation(input){
var fileInput = document.getElementById(input);
var filePath = fileInput.value;
var allowedExtensions = /(\.txt)$/i;
if (!filePath.match(allowedExtensions)) {
alert('Invalid file type. Please Upload .txt format');
fileInput.value = '';
return false;
}
else return true;
}
</script>

Accessing value of javascript file input variable

I am trying to get the filepath of the selected file.
Using the debugger, I see that the file has an property called value which is equal to : "C:\fakepath\filename.txt".
However when I try to access file.value, the filepath is equal to null.I am using Java 8, Struts 1.2, Jsps, and Chrome
Javascript:
function validateFile(file)
{
filepath = file.value; /*This is null*/
return true;
}
Html:
<input type="file" id="theFile[0]" onChange="validateFile(this)"/>
Try this:
function validateFile(fileinput) {
var allowed = "pdf,png";
var filepath=fileinput.value;
var ext = filepath.substr(filepath.lastIndexOf('.')+1);
if (filepath = "" || allowed.search(ext) <= -1) {
fileinput.value='';
alert('Invalid file type');
return false;
}
}
<input type="file" id="inputFile" onChange="validateFile(this)"/>
I guess it wasn't too much work after all :)
function validateFile(file)
{
filepath = file.value;
document.getElementById('result').innerText = filepath;
return true;
}
<input type="file" onChange="validateFile(this)"/>
<div id="result">[result will be here]</div>

Javascript function parameter does not work

In my html form I have 4 file input fields.
<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>
<input type="file" id="one2" name="Title_image2" onchange="check_extension(one3)"/>
<input type="file" id="one3" name="Title_image3" onchange="check_extension(one4)"/>
<input type="file" id="one4" name="Title_image4" onchange="check_extension(one5)"/>
I want to check file extension on inputs using javascript.
My function
function check_extension($field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById("$field_id");
var y = fileinput.value.split(".");
var ext = y[(y.length) - 1];
ext = ext.toLowerCase();
if (allowed[ext]) {
document.chooseF.confirm.disabled = false;
return true;
} else {
alert("This is an unsupported file type. Supported files are: jpg,png");
document.chooseF.confirm.disabled = true;
return false;
}
}
I am using the same function for all the input fields with fieldid as parameter, but it does not work.
onchange="check_extension(one)"
Here one is the Node with the id "one", one is not the string "one"
document.getElementById("$field_id");
Even if $field_id is the id "one", "$field_id" is a different string
So getElementById("$field_id") will give you the node with id "$field_id", not the node with id "one".
Fixes
onchange="check_extension('one')"
and
document.getElementById($field_id)
Also I discourage naming string variables with a leading $
change this:
<input type="file" id="one" name="Title_image1" onchange="check_extension(one)"/>
like so:
<input type="file" id="one" name="Title_image1" onchange="check_extension('one')"/>
Then change this:
function check_extension($field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById("$field_id");
....
like so:
function check_extension(field_id)
{
var allowed = {'jpg': 1, 'png': 1};
var fileinput = document.getElementById(field_id);
...

Pass filename from file upload to text field

I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.
Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/
HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}
A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.

Categories

Resources