4

Prior to submitting a form, I would like to check if a file has been attached and pop up a warning message saying that a file needs to be attached if it hasn't been. I was wondering how to accomplish this using JavaScript or Prototype or JQuery etc?

1 Answer 1

15

Assuming you are using an <input type="file"> field, you can simply check if the element's value is a non-empty string:

<form method="POST">
   <input type="file" id="attachment" />
   <input type="button" onClick="checkAttachment();" value="Send" />
</form>

<script type="text/javascript"> 
   function checkAttachment() {
      if (document.getElementById('attachment').value !== '') {
         alert('File Attached');
      }   
      else {
         alert('No File Attached');
      }
   }
</script> 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.