2009-09-13 14 views

risposta

19

http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-49531485 dice:

valore di tipo DOMString
Quando l'attributo tipo di elemento ha il valore "testo", " lima" o "password", questo rappresenta il contenuto corrente del controllo apposito modulo, in un agente utente interattivo.

<html> 
    <head><title>...</title> 
    <script type="text/javascript"> 
     function foo() { 
     var f = document.getElementById("f1"); 
     alert(""==f.value ? "nothing selected" : "file selected"); 
     } 
    </script> 
    </head> 
    <body> 
    <form> 
     <div> 
     <input id ="f1" type="file" name="x" /> 
     </div> 
    </form> 
    <button onclick="foo()">click</button> 
    </body> 
</html> 
6

Io uso questo javascript:

var file_selected = false; 
function showNoFile() { 
    if(!file_selected) { alert('No file selected!'); } // or anything else 
} 

con questo html per il pulsante di file:

<input type='file' onchange="file_selected = true;" ...> 
.... 
<input type='submit' onclick='showNoFile();'> 

speranza che aiuta!

+0

Penso che questa sia la migliore risposta. Se vuoi fare una richiesta AJAX quando qualcuno sceglie un file, la funzione 'onchange' è ciò che desideri. Se usi semplicemente "onclick", si attiva quando viene aperta la finestra di dialogo Scegli file, ma prima che venga selezionato un file. –

+1

non funziona in chrome ... se si sceglie un file, non si sceglie nuovamente il file il file_selected rimane vero che non è corretto. –

0

Allora supponiamo di avere una qualche forma HTML e si dispone di un ingresso di caricamento di file personalizzato:

<label for="imageUploadButton"> 
<span class="btn" style="padding-left: 10px;">Click here for uploading a new picture</span> 
</label> 
<input type="file" name="avatar_picture" accept="image/gif,image/jpeg,image/png" id="imageUploadButton" style="visibility: hidden; position: absolute;"> 

e si desidera verificare il nome del file che l'utente ha scelto/selezionato:

Utilizzando jquery

<script type="text/javascript"> 
    $(function() { 
    $("input:file").change(function(){ 
     var fileName = $(this).val(); 
     alert(fileName); //Do with the filename whatever you want 
    }); 
    }); 
</script> 

@https://stackoverflow.com/a/5670938/2979938

Per quelli che usano requireJS:

$("input:file").change(function() { 
    var fileName = $(this).val(); 
    alert(fileName); //Do with the filename whatever you want 
}); 
Problemi correlati