简体   繁体   中英

Jquery validate elements having similar names

Hi I am trying to validate all files having similar names

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 () { ....}

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

What you have tried will not work, since the val() method returns the value of the first element in the set of matched elements. In other words, it will only tell you if File1 is empty. You will need loop over each element and check for an empty value, or use a simple if statement.

The script you have will check the condition for just the first input type of File. You need to use some looping construct to involve all the three fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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