submit in form with jquery not working

4

I have a form and inside this form I have an input of type file.

<form id="formulario" method="post" action="upload.php">
  <input id="imagem" name="imagem" type="file" class="da-custom-file customfile-input" >
</form> 

and in jQuery I've tried trying to give submit in the form:

$('#imagem').live('change',function(){

  $('#formulario').submit(function(){
    alert('teste');
  });                   
});

So submit does not work. In case it does not give the alert () with the message teste .

Does anyone have any idea what I might be doing wrong?

    
asked by anonymous 16.06.2014 / 19:19

1 answer

10

Almost there, but you need to separate the code:

  • You must attach alert() to submit of form;
  • In the event that you hear the change of input , you should trigger the submission of the form.
  • JSFiddle Example

    // ao alterar o elemento #imagem
    $('#imagem').on('change',function(){ 
       $('#formulario').submit();
    });
    
    // ao submeter o formulário #formulario
    $('#formulario').submit(function(){
        alert('teste');
    });
    

    I've changed .live() by .on() because in recent versions of jQuery the recommendation is to use .on() .

    Note:
    A file upload form should contain the enctype attribute :

    enctype="multipart/form-data"
    

    Getting:

    <form id="formulario" method="post" action="upload.php" enctype="multipart/form-data">
    ...
    </form>
    
        
    16.06.2014 / 19:34