简体   繁体   English

提交表单时文件输入(标签)没有值(AJAX)

[英]File input (label) has no value when submitting the form (AJAX)

I have a form with <input type="file"> .我有一个带有<input type="file">的表单。 It has display:none, so to style it I'm using a label.它有显示:无,所以我使用的是 label。 Every required input in the form has a "required" class.表格中每个必需的输入都有一个“必需的”class。 When it's empty the form won't be sent and there is a red border around the empty input.当它为空时,表单将不会被发送,并且空输入周围有一个红色边框。 The problem is that when I'm trying to validate my form ("required" class is on the label since input file has display:none) and the form validation reads it like it's always empty (no matter if I upload a file or not).问题是当我尝试验证我的表单时(“必需”class 在 label 上,因为输入文件有显示:无)并且表单验证读取它就像它总是空的(无论我是否上传文件)。

// head
<script>
        $(function () {

        $('#form').on('submit', function (e) {

            e.preventDefault();
            
            let sendForm = true;
            $('.required').each(function(){
                if ($(this).val() == ''){
                    $('#add').addClass('error');
                    $(this).addClass('error');

                    sendForm = false;
                } else {
                    $(this).removeClass('error');
                }
            })

            if (sendForm) {
                $.ajax({
                    type: "post",
                    url: 'php/php.php',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function () {
                        document.getElementById("text").innerHTML = "success";
                        document.getElementById("add").style.border = "2px solid green";
                        $("#add").fadeOut(3000);
                    },
                    error: function () {
                        document.getElementById("text").innerHTML = "error";
                        document.getElementById("add").style.border = "2px solid red";
                    }
                });
            }

        });

        });
</script>
<form id="form" method="POST" action="php/php.php" enctype="multipart/form-data".>

<input type="text" name="Name" id="name" class="required"><br>

Image (jpg, png):
  <label for="upload_image" id="file_style" class="required">File</label>
                            
  <input type="file" style="display:none;" id="upload_image" name="Image" accept="image/*" onchange="loadFile(event)">
  <br>
  <img id="output">
                            
  <script>
    var loadFile = function(event) {
      var output = document.getElementById('output');
      output.src = URL.createObjectURL(event.target.files[0]);
      output.onload = function() {
        URL.revokeObjectURL(output.src)
      }
    };
  </script>

  <input type="number" name="Ing1" class="required">
  <input type="text" name="Ing2" class="required"><br>

  <input type="submit" name="Add" id="add">

</form>
.error{
    border: solid 12px red;
}

(This is only a minimal working example, there is more code. That's why there are "useless" functions.) How can I make it so if the file is uploaded the validation script doesn't see it as undefined? (这只是一个最小的工作示例,还有更多代码。这就是为什么存在“无用”功能的原因。)如果文件被上传,验证脚本不会将其视为未定义,我该如何做到这一点?

First, you don't have a function called "loadFile", I'm not sure if you need it.首先,您没有名为“loadFile”的 function,我不确定您是否需要它。

Second, in the $('.required').each , you loop throw labels , you need to get the input that associated with that label, so one solution is to get it by id after getting for attribute of the label, then check if there are files in the input file, by input.files.length .其次,在$('.required').each中,循环抛出labels ,您需要获取与该 label 关联的input ,因此一种解决方案是在获取 label for属性后通过id获取它,然后检查如果输入文件中有files ,按input.files.length

 .error{ border: solid 12px red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <head> <script> $(function () { $('#form').on('submit', function (e) { e.preventDefault(); let sendForm = true; $('.required').each(function(index, label){ const input = document.getElementById(label.getAttribute('for')) if (.input.files.length){ $('#add');addClass('error'). $(this);addClass('error'); sendForm = false. } else { $(this);removeClass('error'). $('#add');removeClass('error'). } }) if (sendForm) { $:ajax({ type, "post": url. 'php/php,php': data, new FormData(this): processData, false: contentType, false: success. function () { document.getElementById("text");innerHTML = "success". document.getElementById("add").style;border = "2px solid green". $("#add");fadeOut(3000), }: error. function () { document.getElementById("text");innerHTML = "error". document.getElementById("add").style;border = "2px solid red"; } }); } }); }). </script> </head> <body> <form id="form" method="POST" action="php/php.php" enctype="multipart/form-data",> Image (jpg: png): <label for="upload_image" id="file_style" class="required">File</label> <input type="file" style="display;none " id="upload_image" name="Image" accept="image/*"> <br> <input type="submit" name="Add" id="add"> <div id="text"></div> </form> </body>

I think I found the solution.我想我找到了解决方案。 I added this code:我添加了这段代码:

$('.required2').each(function(){
  if ($(this).val() == ''){
    $('#file_style').addClass('error');
    sendForm = false;
  } else {
    $('#file_style').removeClass('error');
  }
})

into my submit function.进入我的提交 function。 I will need to change a few things to suit my needs, but it works as it should.我需要更改一些东西以满足我的需要,但它应该可以正常工作。 Thank you all for the help and ideas how to fix it谢谢大家的帮助和想法如何解决它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM