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>
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.
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.
The following seems to work reliably in Chrome and Firefox (Ubuntu 10.10), I'm unable to check on other platforms at the moment:
$(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'); } } ); });
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With