Checking for attachments in JavaScript
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 开发者_如何学Gobe attached if it hasn't been. I was wondering how to accomplish this using JavaScript or Prototype or JQuery etc?
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>
精彩评论