RSKMR
RSKMR

Reputation: 1892

javascript + preventDefault and stopPropagation not working in addEventListener

I have form and using addEventListener for form submit, I am trying to stop the page loading after form submit.

Note: I want to use addEventListener function.

var test = document.querySelector('.submit');
test.addEventListener('click', checkFunction);

function checkFunction (){
  console.log(test);
  this.preventDefault();
  this.`stopPropagation`();
}
<form>
<input type="text" >
<input type="submit" value="submit" name="submit" class="submit">
</form>

Upvotes: 2

Views: 1913

Answers (2)

Feras Al Sous
Feras Al Sous

Reputation: 1083

You can add the event not this and will be work:

var test = document.querySelector('.submit');
test.addEventListener('click', checkFunction);

function checkFunction (event){
    event.preventDefault();
    event.stopPropagation();

    console.log(event);
}

I hope help you.

Upvotes: 0

Script47
Script47

Reputation: 14530

You need to use event not this, where event refers to the event parameter which is passed to your callback function. In your case this just refers to the submit button.

JSFiddle

Live Example

Open the console to compare e (event) and this.

Upvotes: 1

Related Questions