2015-02-10 55 views
1

我有用戶的表單上載圖像,我想在上傳之前驗證該圖像。所以我在網上找到了這個腳本,它的驗證工作正常,但它不顯示錯誤信息。因爲我不知道如何聲明要顯示的錯誤消息的元素。我只學習javascript,它通常使用document.getElementById("demo").innerHTML = "Hello JavaScript";。但是這個代碼是如此先進,我不知道如何解決它。修復javacode顯示錯誤消息文件上傳

這裏是我的表單中輸入文件。我在第11行中添加了<span class='error-message'></span>。我希望在此span元素中顯示錯誤消息。

<?php 
for($i=0;$i<6;$i++){ 
echo "<div style='padding-left:0' class=\"fileinput fileinput-new col-xs-12 col-sm-6 col-md-4\" data-provides=\"fileinput\"> 
     <div class=\"fileinput-new thumbnail\" style=\"width: 266px; height: 220px;\"> 
      <img src=\"../images/default_image.png\" alt=\"chọn ảnh\"> 
     </div> 
    <div class=\"fileinput-preview fileinput-exists thumbnail\" style=\"width: 277px; height: 220px\"></div> 
     <div> 
      <span class=\"btn btn-default btn-file\"><span class=\"fileinput-new\">Select image</span><span class=\"fileinput-exists\">Change</span><input type=\"file\" onchange=\"getImg(this,500,'jpeg|png')\" id=\"file$i\" name=\"file[]\"></span> 
      <a href=\"#\" class=\"btn btn-default fileinput-exists\" data-dismiss=\"fileinput\">Remove</a> 
      <span class='error-message'></span> 
     </div> 
    </div>"; 
} 
?> 

這裏是Java腳本代碼:

<script> 
function getImg(input,max,accepted){ 
var upImg=new Image(),test,size,msg=input.form; 
msg=msg.elements[0].children[0]; 
return input.files?validate(): 
(upImg.src=input.value,upImg.onerror=upImg.onload=validate); 
    "author: b.b. Troy III p.a.e"; 
function validate(){ 
    test=(input.files?input.files[0]:upImg); 
    size=(test.size||test.fileSize)/1024; 
    mime=(test.type||test.mimeType); 

mime.match(RegExp(accepted,'i'))? 
size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"): 
msg.innerHTML="Upload ready...":  
(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!") 
} 
} 
</script> 

這是筆者這個腳本的工作演示:JSFIDDLE。我如何在我的情況下應用這個?

+1

的Java與JavaScript不這樣就不是指JavaScript作爲Java的。 – epascarello 2015-02-10 04:51:04

回答

0

最簡單的方法是:

在你html的更換:

<span class='error-message'></span> 

有:

而且在你JS更換:

msg=msg.elements[0].children[0]; 

有:

var msg=document.getElementById('error-message');