Allow Select PDF only in JS

2

I would like to know how to do that by choosing the file to upload it to filter by native .pdf extension html or by JS, Jquery.

Using the type="file" it brings all the files.

<!DOCTYPE html>
<html>
<body>

<h1>Selecione o arquivo PDF:</h1>

<h3>Selecione o PDF:</h3>
<form action="/action_page.php">
  <input type="file" name="myFile"><br><br>
  
</form>



</body>
</html>
    
asked by anonymous 03.08.2018 / 22:29

3 answers

4

You can use this way:

<input type="file" accept="application/pdf">

Here has a list of file types and code mime you can use, if you want to use more than one, you can separate with |

Ex:

<input type="file" accept="application/pdf|image/*">

MDN Compatibility List

    
03.08.2018 / 22:47
2

You can use valid Javascript for any browser to do this.

<html>
<body>
    <h1>Selecione o arquivo PDF:</h1>
    <h3>Selecione o PDF:</h3>
    <form action="/action_page.php">
        <input type="file" name="myFile"><br><br>
    </form>

<script>
    var file = document.getElementsByTagName('input').value();
    var tipo = file.split('.').pop();

    if(tipo != 'pdf'){
        alert('Arquivo não suportado');
    }
</script>
</body>
</html>
    
03.08.2018 / 22:44
1

Completely, we have the following answer for your case:

    <!DOCTYPE html>
    <html>
    <body>
    
    <h1>Selecione o arquivo PDF:</h1>
    
    <h3>Selecione o PDF:</h3>
    <form action="/action_page.php">
      <input type="file" accept="application/pdf">
      <br><br>
      
    </form>
    
    </body>
    </html>
    
03.08.2018 / 22:53