Ubmit in form with jquery does not work

Asked

Viewed 1,685 times

4

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

<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’m trying to give the Submit on the form:

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

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

Only that the 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?

1 answer

10

Almost there, but you need to separate the code:

  1. You have to attach the alert() at the submit form;
  2. In the event that hears the change of input, should trigger the sending of the form.

Example in Jsfiddle

// ao alterar o elemento #imagem
$('#imagem').on('change',function(){ 
   $('#formulario').submit();
});

// ao submeter o formulário #formulario
$('#formulario').submit(function(){
    alert('teste');
});

I switched the .live() for .on() because in recent versions of jQuery the recommendation is the use of .on().

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

enctype="multipart/form-data"

Staying:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.