Home > OS >  File input (label) has no value when submitting the form (AJAX)
File input (label) has no value when submitting the form (AJAX)

Time:08-01

I have a form with <input type="file">. It has display:none, so to style it I'm using a label. Every required input in the form has a "required" 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).

// 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" ><br>

Image (jpg, png):
  <label for="upload_image" id="file_style" >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" >
  <input type="text" name="Ing2" ><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?

CodePudding user response:

First, you don't have a function called "loadFile", I'm not sure if you need it.

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.

.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" >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>

CodePudding user response:

I have updated your script code, never touched HTML & CSS file. It worked well on my end. I hope this will help you a little.

<script>
  let sendForm = false,
    fileList;

  function loadFile(event) {
    fileList = event.files;
    sendForm = true;
  }

  $(function () {
    $("#form").on("submit", function (e) {
      e.preventDefault();

      if (sendForm) {
        $(this).removeClass("error");

        $.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";
          },
        });
      } else {
        $(this).addClass("error");

        sendForm = false;
      }
    });
  });
</script>

Regards, Albert

  • Related