简体   繁体   English

jQuery验证具有相似名称的元素

[英]Jquery validate elements having similar names

Hi I am trying to validate all files having similar names 嗨,我正在尝试验证所有具有相似名称的files

These are my input elements 这些是我的输入要素

<form id="MyForm" onsubmit="return validate();">
<input type="file" name="File1"  />
<input type="file" name="File2" />
<input type="file" name="File3" />
</form>

what I am tried is 我被尝试的是

 function validate()
  {
   if($('input[name ^= "File"]').val()=='')
   {
     alert("The field is empty");
     return false;
   }
   }

is this possible ? 这可能吗 ? or need to do like $('input[type=file]').each(function () { ....} 或需要做类似$('input[type=file]').each(function () { ....}

This will work 这会起作用

$('input[name^=file]').each(function() {
    if($(this).val() === '')
    {
        alert('The field is empty');
        return false;
});

This is because $('input[name^=file]') will return multiple elements so you need to iterate through them to check individual element 这是因为$('input[name^=file]')将返回多个元素,因此您需要遍历它们以检查单个元素

What you have tried will not work, since the val() method returns the value of the first element in the set of matched elements. 您尝试过的方法将不起作用,因为val()方法将返回匹配元素集中第一个元素的值。 In other words, it will only tell you if File1 is empty. 换句话说,它只会告诉您File1是否为空。 You will need loop over each element and check for an empty value, or use a simple if statement. 您将需要遍历每个元素并检查是否为空值,或使用简单的if语句。

The script you have will check the condition for just the first input type of File. 您拥有的脚本将仅检查File的第一个输入类型的条件。 You need to use some looping construct to involve all the three fields. 您需要使用一些循环构造来涉及所有这三个字段。

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

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