Javascript function parameter does not work - javascript

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);
...

Related

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

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.

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>

How to determining if a file has been selected in JavaScript?

I'm using JavaScript to validate an uploading form, one of the conditions is to check if any file has been selected. I thought this would be simple, but I can't get it to work. Is this code invalid? The var file works with other conditions so it's not that
var file = document.getElementById('file');
if(file.value =="") {
alert("no file selected")
return false;
}
<input name="uploaded" type="file" id="file" />
You can use the following example:
var fileInput = document.getElementById('file');
fileInput.onchange = function () {
var input = this.files[0];
if (input) {
//process input.
} else {
alert("Please select a file.");
}
};
Hope this helps.

File type validation!! for generated input file tag elements

JSP:
----
<div ID="items">
input id="file5" type="file" path="files" name="files" size="40" /> Other documents
</div>
Javascript:
-----------
<script type="text/javascript">
var items=1;
function AddItem() {
var div=document.getElementById("items");
var button=document.getElementById("add");
items++;
newitem="";
newitem+="<input type=\"file\" path=\"files\" name=\"files\"";// + items;
newitem+="\"id=file"+items;
newitem+="\" size=\"40\"> Other documents";
newitem+=" <input type=\"button\" class=\"button\" id=\"delButton"+items;
newitem+="\" value=\"\" name=\"button"+items;
newitem+="\" onclick=deletethisRow("+items+")>";
newnode=document.createElement("div");
newnode.setAttribute("id","child"+items);
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
function deletethisRow(obj){
var fileElement=document.getElementById("file"+obj);
var buttonElement=document.getElementById("delButton"+obj);
var childDivName="child"+obj;
if (buttonElement) {
var child = document.getElementById(childDivName);
var parent = document.getElementById("items");
parent.removeChild(child);
}
}
</script>
---
Above is the JSP code as well as JavaScript snippets.. I'm trying to validate the input files....
I want to allow only jpg,png,pdf,doc,docx file types to be upload??
Any thoughts on how to achieve this?
Thanks and regards,
Satish Krishnamurthy
You can change your input tag:
<input type="file" name="pic" id="pic" accept=".someext, image/gif, image/jpeg" />
But please don't rely on client-side validation. Check it server-side or people can disable the client-side checks and upload even executable scripts.
function Checkfilesextension()
{
var fileToupload = document.getElementById('elementId');
var fileName = fileToupload .value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
ext.toLowerCase
if(ext =="GIF" || other extension) // add other extensions
{
return true;
}
else
{
alert("Upload only the allowed files");
return false;
}
}
This would check for the extension of the files....have not tested the code though

Categories

Resources