2016-07-24 39 views
1

我想告诉我的错误,如果“fileToUpload”为空(用JS显示错误),并停止刷新页面,如果“fileToUpload”为空PHP停止形态刷新显示错误的js

<form method="post" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input class='new_post' type="submit" value="Upload Image" name="submit"> 
</form> 

$('.new_post').click(function() { 
    var get_photo = $('#fileToUpload').get(0).files.length; 

    // If 0 file show error 
    if (get_photo == 0) { 
     openandclose('.error_box' , 'emptyyyy.', 1700); 
     $('.error_box').focus(); 
     return false; 
    } 
}); 
+1

那么,你的问题是什么?测试它是否有效。我建议你在表单上使用提交事件,而不是点击按钮。但是,如果你想让我们更好地帮助你,请发布一个jsfiddle。 – Loenix

+0

所以,可能get_photo == 0是错误的。我们无法测试 – Loenix

+0

您可以指定问题吗? bcoz我在代码运行器中运行了你的代码,并且工作正常,所以我删除了我的答案。我正在取消您的参考。请指明您的问题。 – Iceman

回答

0

添加ID到您的形式是这样的<form method="post" enctype="multipart/form-data" id="myform">并在您的JavaScript附加检查功能作为回调到表单提交事件而不是按钮单击事件,如$('#myform').submit()

$('#myform').submit(function() { 
 
    var get_photo = $('#fileToUpload').get(0).files.length; 
 
    // If 0 file show error 
 
    if (get_photo == 0) { 
 
    /* 
 
    openandclose('.error_box', 'emptyyyy.', 1700); 
 
    $('.error_box').focus(); 
 
    */ 
 
    alert("EMPTY!!"); 
 
    return false; 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form method="post" enctype="multipart/form-data" id="myform"> 
 
    Select image to upload: 
 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
 
    <input class='new_post' type="submit" value="Upload Image" name="submit"> 
 
</form>

+0

但是,我认为OP的代码中没有错误,应该可以工作。这只是一个推荐的答案(这就是为什么我之前删除它) – Iceman

+1

感谢工作完美! –

0

此代码可以帮助你out.Upon点击它会检查文件是否被选中与否按钮,返回真/假。因此。

<form method="post" enctype="multipart/form-data" onsubmit="return funccheck();"> 
Select image to upload: 
<input type="file" name="fileToUpload" id="fileToUpload"> 
<input class='new_post' type="submit" value="Upload Image" name="submit"> </form> 
<script> 
function funccheck() { 
var get_photo = $('#fileToUpload').get(0).files.length; 
// If 0 file show error 
if (get_photo == 0) { 
openandclose('.error_box' , 'emptyyyy.', 1700); 
$('.error_box').focus(); 
return false; //stops page loading 
} 
return true; // initiates page loading 
}); 
</script> 
+0

感谢但不工作兄弟 –

0

试试这个:

$('.new_post').click(function(e) { var get_photo = $('#fileToUpload').get(0).files.length; // If 0 file show error if (get_photo == 0) { openandclose('.error_box' , 'emptyyyy.', 1700); $('.error_box').focus(); e.preventDefault(); return false; } });

变量e是事件,该函数的preventDefault将提交如果没有文件停止形式。

+0

在jquery事件回调中返回false与preventDefault的返回值相同,因此不需要此添加。 – Iceman

+0

Noy一定,我目睹了一些奇怪的错误,这是必要的,这也是“正确”的方式来做到这一点 – FMashiro

+0

实际上,jquery在内部调用了'e.preventDefault'和'e.stopPropagation'。你可以按照jquery团队邮件列表存档 - >正确的方法来停止,以及引用这个:http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false。这就是说,如果你能够复制'return false'失败的情况,我会非常感兴趣。 :D – Iceman