D
D
Dasha2015-09-24 00:46:50
JavaScript
Dasha, 2015-09-24 00:46:50

Why doesn't the form submit on the change event?

$("input[type=file]").on('change', function (e) {

        $($(this).siblings('input[type=submit]')).click( function( e ) {
           
            console.log(this);
            e.preventDefault();

        } );

    });

Why doesn't it work?
If I just click on the send button, it works, but it would be necessary that after loading the picture it would already work.
What could be the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Inchin ☢, 2015-09-24
@In4in

The form can also work by pressing Enter , for example. So, it's not right to catch a click on a submit.
You can do it like this:

$("form").on("submit", function(e){
  $("input[type=file]").val()||e.preventDefault();
});

Or like this:
var acess = false;

$("input[type=file]").one("change", function(){
  acess = true;
});

$("form").on("submit", function(e){
  acess||e.preventDefault();
});

Or even cooler:
var form = $("form");

form.on("submit", function(){
  e.preventDefault();
}).siblings("input[type=file]")
 .one("change", function(){
   form.off("submit");
});

Why is your code not working
//При выборе файла
$("input[type=file]").on('change', function (e) { 
  //Ставим обработчик
  $($(this).siblings('input[type=submit]')).click( function( e ) { 
      //Который запрещает отправку формы по нажатию на кнопку
     e.preventDefault();
  });
});

UPD: In general, there is a wonderful required attribute - and no JS is needed.

A
Aram Aramyan, 2015-09-24
@GreenBee

So you have e.preventDefault(); which just cancels the form submission.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question