jquery如何判断from中的数组是否为空

时间:2017-04-26 08:45:48

标签: javascript jquery

也许我所表达的问题的标题不是很清楚。让我说说具体一点。我有一些HTML代码如下:

<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="js/jquery.js"></script>
</head>

<body>
    <form action="" method="post" enctype="multipart/form-data" onsubmit="return checkpost();">
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
        </p>
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
        </p>
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
        </p>
        <p> <input id="submit" type="submit" value="submit" /></p>
    </form>
</body>

<script>
    function checkpost() {

    }
</script>

</html>

对于我的php编程,我必须检查是否有3张图片被选中,但我不知道如何在我的js代码中检查它。 对不起,我的英语不好使问题不太清楚,但感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

使用jquery,

尝试此操作

&#13;
&#13;
$('#submit').on('click', function() {
  pictures = $('[name="picture[]"]');
  // filter the pictures element which has some values
  filled = pictures.filter(function() {
    return this.value.length
  });
  // if all images are added then return true
  if (filled.length === pictures.length) {
    return true;
  }
  alert('Please select all images');
  return false;
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data">
  <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
  </p>
  <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
  </p>
  <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
  </p>
  <p> <input id="submit" type="submit" value="submit" /></p>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

You could disable the submit input until an array of values no longer contains a null;

<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <script src="js/jquery"></script>
</head>

<body>
    <form action="" method="post" enctype="multipart/form-data" onsubmit="return checkpost();">
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" onchange="changeHandler" />
        </p>
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
        </p>
        <p> <input name="picture[]" type="file" accept="image/gif, image/jpeg" />
        </p>
        <p> <input id="submit" type="submit" value="submit" disabled /></p>
    </form>
</body>

<script>
    var inputs = $("input[type=file]"),
        submit = $("input[type=submit");
    inputs.on("change", changeHandler);

    function checkpost() {
        // carry out action
    }

    function changeHandler() {
        var a = [];

        for(var i = 0; i < inputs.length; i++) {
            a.push($(inputs[i]).val());
        }

        a.indexOf("") === -1 ? submit.prop("disabled", false) : submit.prop("disabled", true);
    }
</script>

</html>