Javascript onChange事件未在输入类型文件中触发

时间:2017-04-07 09:32:31

标签: jquery

我在'Scripts'文件夹中使用javascript文件来检查验证文件大小然后上传图像。但是,有时change事件未触发。我的代码中有什么错误?

var fileLogo = "";

$(document).on("change", "#idfileLogo", function(e) {
  var file_size = $(this)[0].files[0].size;
  if (file_size > 1000141) {
    $("#txtfileLogo").attr("placeholder", "Upload Image");
    var message = "Image size is greater than 1MB.";
    showErrormesssage(message);
    return false;
  }
  fileLogo = $(this).val();
  var ext = fileLogo.split('.').pop();
  if (ext == "x-png" || ext == "jpeg" || ext == "gif" || ext == "jpg") {
    $("#txtfileLogo").attr('placeholder', $(this).val().split('\\').pop());
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" style="height: 35px !important" id="txtfileLogo" class="form-control input-lg" disabled placeholder="Upload Image">
<div class="input-group-btn">
  <div class="browse btn btn-primary"><i class="glyphicon glyphicon-search"></i> Browse<input type="file" accept="image/*" id="idfileLogo" name="fileUploadLogo" class="file"></div>
</div>

1 个答案:

答案 0 :(得分:0)

你有这个问题,因为你的脚本在你的html标签之前,当你的脚本运行时,没有“idfileLogo”标签。

将这些标记放在html标记之后或使用jQuery事件来确保您的内容已加载。例如:

    var fileLogo = "";
    $(document).ready(function() {
        $(document).on("change", "#idfileLogo", function(e) {
          var file_size = $(this)[0].files[0].size;
          if (file_size > 1000141) {
            $("#txtfileLogo").attr("placeholder", "Upload Image");
            var message = "Image size is greater than 1MB.";
            showErrormesssage(message);
            return false;
          }
          fileLogo = $(this).val();
          var ext = fileLogo.split('.').pop();
          if (ext == "x-png" || ext == "jpeg" || ext == "gif" || ext == "jpg") {
            $("#txtfileLogo").attr('placeholder', $(this).val().split('\\').pop());
          }
        });
    });