0

I have this application with a file input and a submit input. I want the submit input to be disabled until the file input has a value. How do I check this kind of information with JS? I tried adding a "required" to the file input, but it still doesn't work...

Should I just use PHP and check if $_FILE isset()?

  • Aren't you already doing that? Isn't your submit button disabled until it has a value? – MinusFour Jan 06 '16 at 03:54
  • *"The submit input is disabled until ..."* implies that the JS side already works. Please clarify. – Leon Adler Jan 06 '16 at 03:56
  • @LeonAdler I worded the instructions wrong! Sorry... –  Jan 06 '16 at 03:59
  • Possible duplicate of [How to check if input file is empty in JQuery](http://stackoverflow.com/questions/25793880/how-to-check-if-input-file-is-empty-in-jquery) – MinusFour Jan 06 '16 at 04:05

2 Answers2

0

Should I just use PHP and check if $_FILE isset()?

It is good practice to ensure that the server gets what is expected. So yes, additional checks for a file and eventual mischiefs should also be done on the server.

Here is an example of what you want on the client-side.

JSFiddle

HTML

<form name="fileForm" onchange="changed()">
  <input type="file" name="image">
  <input type="submit" name="submit" disabled>
</form>

JavaScript

function changed() {
    var form = document.forms.fileForm;
    if(form.image.value.length > 0) {
        form.submit.removeAttribute("disabled");
    } else {
        form.submit.setAttribute("disabled", "");
    }
}
E. Sundin
  • 4,103
  • 21
  • 30
0

Try this

<form name="form1">
          <input type="file" name="image" id="file_upload">
          <input type="submit" name="submit" id="btn_submit" >
        </form>

jQuery(document).ready(function()
{    
    /*To disable the button on load*/ 
    jQuery("#btn_submit").attr('disabled','disabled'); 


     jQuery("#file_upload").change(function()
    {       
       var file_value= jQuery(this).val();
      if(jQuery(this).val() === '')
      {                                          

        jQuery("#btn_submit").attr('disabled','disabled');                                         
      }
      else
      {
        jQuery("#btn_submit").removeAttr('disabled');
      }
  });
});
Domain
  • 11,562
  • 3
  • 23
  • 44