Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
Input file does not run function if empty

If I insert png it works, if I insert jpg it works, but if I leave the file empty it doesn't work, why? The file should be png or empty.

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0].type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || fileTypecheck.length == 0){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file"  onchange="loadFile(event)" accept="image/png">

<button onclick="myFunction()">Click me</button>

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

When there is no file the index of files[0] does not excist. You can add a question mark (Optional_chaining) to files[0] so it does not break down when there are no files. Then you can change fileTypecheck.length== 0 to !fileTypecheck since it will be undefined when there is no file.

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0]?.type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || !fileTypecheck){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file" accept="image/png">

<button onclick="myFunction()">Click me</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

When an <input type="file"/> has no files selected its HTMLInputElement.files property is empty, so files[0] is undefined.

BTW, you should not rely on the browser to always accurately tell you of a file's type: browsers typically populate the File.type property from their host OS's file-extension-to-MIME-type registry which is not reliable and often outdated.

That said, change your code to this: note that I've added defensive programming steps to actually verify things instead of making assumptions:

function myFunction() {

    const inp = document.getElementById("file");
    if( !inp || inp.type !== 'file' ) throw new Error( "'file' input element not found." );
    
    if( inp.files.length !== 1 ) {
        alert( "Please select a single file first." );
        return;
    }

    const file = inp.files[0];
    if( file.type === 'image/png' ) {
        // OK
    
    }
    else {
        alert( "Please select a PNG file." );
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda