user6247920
user6247920

Reputation:

JavaScript: Submit and Prevent

I try to trigger form submitting and prevent the submission at the same time. What I mean: When you select a file, JS will attempt to submit, but will also run a function (onsubmit) that prevents the action.

And that's my code (No jQuery, just trying to make it look like php):

var $form, $file, $files;

$form  = document.querySelector('form#form-1'),
$file  = $form.querySelector('input[type="file"]'),
$files = null;

$file.onchange = function($e){
    $files = $e.target.files;
    $form.submit();
};

$form.onsubmit = function($e){
    $e.preventDefault();
    console.log('Default Prevented');

    // Xhr will go here, if the browser will prevent
    // it from being submitted
};

I know that the problem might be because I'm confusing the browser and tells once to submit and then to prevent, but how can I make it work as expected? I'm planning to insert xhr within the $form.onsubmit function that should to the required job, but It won't, at least as long as the browser will submit the function without preventing it from being submitted.

Upvotes: 3

Views: 65

Answers (1)

dfsq
dfsq

Reputation: 193271

Instead of invoking onsubmit handler manually, move AJAX call into separate function and call it from both handlers:

$file.onchange = function($e){
    $files = $e.target.files;
    sendForm($form)
};

$form.onsubmit = function($e) {
    $e.preventDefault();
    sendForm($form)
};

function sendForm(form) {
    // Xhr will go here, if the browser will prevent
    // it from being submitted
    console.log('send form with AJAX');
}

UPD. If you really-really want to trigger event you should do it with dispatchEvent method, as (thanks @NathanP. for pointing it out) just calling $form.submit() is not going to trigger it:

$file.onchange = function($e){
    $files = $e.target.files;
    var event = new Event('submit', {
        bubbles: true,
        cancelable: true 
    });
    $form.dispatchEvent(event);
  };

  $form.onsubmit = function() {
      console.log('send form with AJAX');
      return false; // use return false; to prevent event in case of onsubmit handler, and e.preventDefault for addEventListener event handlers
  }

But I would avoid triggering native events like this, since helper funtion way of doing what you need is way simpler to reason about, test and more reliable cross-browser-wise.

Upvotes: 2

Related Questions