我有一个标准的输入字段:显示确认
<input type="file">
在我的形式
,但我看不到它,这样我可以用我自己的形象为按钮(如在使用这种方法时,没有给用户确认他们的文件被选中的确认,因为标准输入框是隐藏的,所以他们永远不会看到文件名。
所以我的问题归结为:如何检测文件已被选中,然后在页面上显示的东西(不是一个警告框)?理想情况下,我只想显示一个小图标或一些文字说“选择文件”。
Jquery很好,但如果没有办法做到这一点,我更喜欢这个。谢谢!
我有一个标准的输入字段:显示确认
<input type="file">
在我的形式
,但我看不到它,这样我可以用我自己的形象为按钮(如在使用这种方法时,没有给用户确认他们的文件被选中的确认,因为标准输入框是隐藏的,所以他们永远不会看到文件名。
所以我的问题归结为:如何检测文件已被选中,然后在页面上显示的东西(不是一个警告框)?理想情况下,我只想显示一个小图标或一些文字说“选择文件”。
Jquery很好,但如果没有办法做到这一点,我更喜欢这个。谢谢!
这是一个非常简单的方法来做到这一点,而不使用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;
}
这正是我正在寻找的,谢谢!我希望我能够得到赞扬,但我没有15声望,对不起! – NeilSmith 2014-11-07 16:06:05
没问题我很高兴它有帮助 – 2014-11-08 19:09:13
如果你听的元素有关的变化时,你会当一个文件被选中知道:
$('input').change(function(){
console.log($(this).val());
});
您可以使用$(this).val()
,如果你想显示的文件名。如果你不想使用jQuery,你正在寻找onchange
事件。
这是你正在寻找的代码。 为了更好的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>
如果你问一个办法做到这一点没有的jQuery或JavaScript(是的,包含jQuery),你不能。你将不得不使用一个脚本来监听输入字段的变化。 – David 2014-11-06 12:40:34