2014-11-06 36 views
0

我有一個標準的輸入字段:顯示確認

<input type="file"> 
在我的形式

,但我看不到它,這樣我可以用我自己的形象爲按鈕(如在使用這種方法時,沒有給用戶確認他們的文件被選中的確認,因爲標準輸入框是隱藏的,所以他們永遠不會看到文件名。

所以我的問題歸結爲:如何檢測文件已被選中,然後在頁面上顯示的東西(不是一個警告框)?理想情況下,我只想顯示一個小圖標或一些文字說「選擇文件」。

Jquery很好,但如果沒有辦法做到這一點,我更喜歡這個。謝謝!

+0

如果你問一個辦法做到這一點沒有的jQuery或JavaScript(是的,包含jQuery),你不能。你將不得不使用一個腳本來監聽輸入字段的變化。 – David 2014-11-06 12:40:34

回答

3

這是一個非常簡單的方法來做到這一點,而不使用jQuery。你將不得不改變id的符合你的html當然。

下面是一個例子的jsfiddle鏈接:http://jsfiddle.net/larryjoelane/rrns0k4e/1/

HTML部分:

<input id="file-select" type="file"> 

<div id="file-selected"></div> 

JavaScript部分:

//on change event listener for #file-select 
document.getElementById("file-select").onchange = function() { 

    //call getFileSelected method 
    getFileSelected(); 

}; 

function getFileSelected(){ 

    //get the value of the input file element 
    var getFileSelected = document.getElementById("file-select").value; 

    //display the results of the input file element 
    //you can append something before the getFileSelected value below 
    //like an image tag for your icon or a string saying "file selected:" 
    //for example. 
    document.getElementById("file-selected").innerHTML = getFileSelected; 

} 
+0

這正是我正在尋找的,謝謝!我希望我能夠得到讚揚,但我沒有15聲望,對不起! – NeilSmith 2014-11-07 16:06:05

+0

沒問題我很高興它有幫助 – 2014-11-08 19:09:13

1

如果你聽的元素有關的變化時,你會當一個文件被選中知道:

$('input').change(function(){ 
    console.log($(this).val()); 
}); 

您可以使用$(this).val(),如果你想顯示的文件名。如果你不想使用jQuery,你正在尋找onchange事件。

小提琴:http://jsfiddle.net/cphutg90/

0

這是你正在尋找的代碼。 爲了更好的UI表現,看在Internet Explorer 8+

HTML和JavaScript:

<!DOCTYPE html> 
 
<!-- 
 
To change this license header, choose License Headers in Project Properties. 
 
To change this template file, choose Tools | Templates 
 
and open the template in the editor. 
 
--> 
 
<html> 
 
    <head> 
 
     <title>File Picker</title> 
 
     <meta charset="UTF-8"> 
 
     <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
 
     <script type="text/javascript"> 
 
      function fileValidator() 
 
      { 
 
       var fileName=document.forms["FileForm"]["fileName"].value.replace("C:\\fakepath\\", ""); 
 
       var response=confirm("Are you sure to Upload '"+fileName+"'?"); 
 
       console.log(response); 
 
       if(response==false) 
 
       { 
 
        document.forms["FileForm"]["fileName"].value=""; 
 
       } 
 
      } 
 
     </script> 
 
    </head> 
 
    <body> 
 
     <form name="FileForm" action="" method="Post"> 
 
      <table> 
 
       <tr> 
 
        <td><input type="file" name="fileName" onchange="javascript:fileValidator();"/></td> 
 
       </tr> 
 
       <tr> 
 
        <td><input type="submit" value="Upload"/></td> 
 
       </tr> 
 
      </table> 
 
     </form> 
 
    </body> 
 
</html>