duandu8202
2015-01-27 06:17
浏览 222

使用jQuery判断文件输入字段是否为空

I have a PHP form with a file input field, and two text input fields. What I want to do is use jQuery to check if the file input field is empty, and if it's not, then show a specific div, but the following code does not work:

<input type="file" name="blog-entry-image" id="blog-entry-image" />

var fileInput = $.trim($("#blog-entry-image").val());
if (fileInput.length > 0) {
        $("#new-blogentry").click(function() {
        $("#sending").show();
        return true;
    }); 
}

"new-blogentry" is the submit button, and "sending" is a div with an animated gif.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douxianwu2221 2015-01-27 06:23
    已采纳
    <input type="file" name="blog-entry-image" id="blog-entry-image" />
    
    $(document).ready(function (){
        $("#blog-entry").click(function() {
            var fileInput = $.trim($("#blog-entry-image").val());
            if (fileInput && fileInput !== '') {      
                    $("#sending").show();
                    return true;    
            }
      });
    });
    
    已采纳该答案
    打赏 评论
  • dsgdhtr_43654 2015-01-27 06:23

    Change fileInput.length > 0 to

    fileInput != "" && fileInput.trim() != ""
    
    打赏 评论
  • dongying9756 2015-01-27 06:24

    You have things backwards. You need to get the file input value after the user clicks.

    $('#new-blogentry').click(function() {
        var fileInput = $.trim($("#blog-entry-image").val());
        if (fileinput.length > 0) {
            ...
        }
    });
    
    打赏 评论
  • doulan0297 2015-01-27 06:58
    if($('#new-blogentry').val()==''))
    

    is enough to check if the file input is empty

    打赏 评论
  • duanlie7447 2015-01-27 08:57

    I suggest you to use jquery validator plugin for all frontend based validation http://jqueryvalidation.org/

    打赏 评论

相关推荐 更多相似问题