Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disable submit button until file selected for upload

I have a form for uploading images. I'd like to disable the submit button, until user selects an image to upload. I'd like to do it with jQuery. Currently I have a JavaScript function that prevent user from submitting the form more than once by disabling it on submit. It'd be nice to combine this functionality with the new one.

Here's what I've got now:

<script type="text/javascript"> function submitonce(theform) {     //if IE 4+ or NS 6+     if (document.all || document.getElementById) {         //screen thru every element in the form, and hunt down "submit" and "reset"         for (i = 0; i < theform.length; i++) {             var tempobj = theform.elements[i]             if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")             //disable em             tempobj.disabled = true         }     } } </script> <form name="form" enctype="multipart/form-data" method="post" action="upload.php" onSubmit="submitonce(this)">  <input type="file" name="my_field" value="" />  <input type="submit"> </form> 
like image 851
santa Avatar asked Oct 29 '10 22:10

santa


People also ask

How do you disable submit button until form is filled?

Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.

How do I disable the submit button?

1.1 To disable a submit button, you just need to add a disabled attribute to the submit button. $("#btnSubmit"). attr("disabled", true); 1.2 To enable a disabled button, set the disabled attribute to false, or remove the disabled attribute.


1 Answers

The following seems to work reliably in Chrome and Firefox (Ubuntu 10.10), I'm unable to check on other platforms at the moment:

jQuery

$(document).ready(     function(){         $('input:file').change(             function(){                 if ($(this).val()) {                     $('input:submit').attr('disabled',false);                     // or, as has been pointed out elsewhere:                     // $('input:submit').removeAttr('disabled');                  }              }             );     }); 

html

<form action="#" method="post">     <input type="file" name="fileInput" id="fileInput" />     <input type="submit" value="submit" disabled /> </form> <div id="result"></div> 

Demo at JS Fiddle.

like image 156
David Thomas Avatar answered Oct 09 '22 12:10

David Thomas