javascript - 选择文件时的操作

时间:2015-02-24 13:14:19

标签: javascript jquery html

我试图让Javascript做一些事情,在这种情况下,当用户选择文件时显示警告。我不确定我的代码是否真的进入我的javascript,这是我的代码:



function showNoFile() {
    if(document.getElementById("video-file-upload").value != "") {
   		alert("yeap");
   }
}

/*****************
   UPLOAD BUTTON
******************/

.file-wrapper {
  cursor: pointer;
  display: inline-block;
  overflow: hidden;
  position: relative;
  margin:10px;
}

.file-wrapper input {
  cursor: pointer;
  font-size: 100px;
  height: 100%;
  -moz-opacity: 0.01;
  opacity: 0.01;
  position: absolute;
  right: 0;
  top: 0;
}

.file-wrapper .button {
  background: #F3A662;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  display: inline-block;
  font-size: 11px;
  font-weight: bold;
  margin-right: 5px;
  text-transform: uppercase;
}

<form id="video_uploader" name="video_uploader" action="uploader.php" method="post" enctype="multipart/form-data">
							<span class="file-wrapper btn ad-choice">
								<input type="file" name="file" id="video-file-upload" /> 
								<span class="button">Choose a video</span>								
							</span>						
							<br/>		
							<input type="submit" name="submit" value="Submit" />
						</form>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

在DOM ready

上使用它
$("#video-file-upload").change(function(){
    if($(this).val() != ""){
     alert("some file selected");
    }
});

Fiddle

答案 1 :(得分:0)

使用javascript:

function showNoFile() {
   if(this.value != "") {
      alert("yeap");
   }
}

document.getElementById("video-file-upload").onchange = showNoFile;

function showNoFile() {
    if(this.value != "") {
   		alert("yeap");
   }
}

document.getElementById("video-file-upload").onchange = showNoFile;
/*****************
   UPLOAD BUTTON
******************/

.file-wrapper {
  cursor: pointer;
  display: inline-block;
  overflow: hidden;
  position: relative;
  margin:10px;
}

.file-wrapper input {
  cursor: pointer;
  font-size: 100px;
  height: 100%;
  -moz-opacity: 0.01;
  opacity: 0.01;
  position: absolute;
  right: 0;
  top: 0;
}

.file-wrapper .button {
  background: #F3A662;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  display: inline-block;
  font-size: 11px;
  font-weight: bold;
  margin-right: 5px;
  text-transform: uppercase;
}
<form id="video_uploader" name="video_uploader" action="uploader.php" method="post" enctype="multipart/form-data">
							<span class="file-wrapper btn ad-choice">
								<input type="file" name="file" id="video-file-upload" /> 
								<span class="button">Choose a video</span>								
							</span>						
							<br/>		
							<input type="submit" name="submit" value="Submit" />
						</form>

答案 2 :(得分:0)

if (document.getElementById("video-file-upload").files.length == 0) {
  alert("yeap");
}

检查files.length是否等于0.