I have a script that is scanning a page for all buttons and logging the click of each into the database. Unfortunately the button data will not submit until the second click am I using the addEventListener and removeEvent listener in the correct location?
var trkButtons = document.getElementsByTagName('input');
for (var i = 0; i < trkButtons.length; ++i) {
//submit button
if (trkButtons[i].getAttribute("type") == "submit") {
trkButtons[i].addEventListener("click", addBtnClickListener, false);
}
//image button
if (trkButtons[i].getAttribute("type") == "image") {
trkButtons[i].addEventListener("click", addBtnClickListener, false);
}
//file upload
if (trkButtons[i].getAttribute("type") == "file") {
trkButtons[i].addEventListener("click", addBtnClickListener, false);
}
else { }
}
function addBtnClickListener(e) {
e.preventDefault();
this.click();
this.removeEventListener('click', addBtnClickListener, false);
var eventType = "button.click";
var ctrBtnText = this.value;
track(this, eventType, '', '', ctrBtnText, '', '', '');
}
Okay, so here is what your addBtnClickListener
function does:
Form submission works the second time because first time, at step 3 you remove this event handler which actually prevents form submission.
If you don't wanna prevent default behavior like form submitting, file upload dialog opening, etc. then you should not use e.preventDefault()
.
Possible solution:
function addBtnClickListener(e) {
// the code below will be executed, before the form is submitted
// no need for other action if this is all we do
var eventType = "button.click";
var ctrBtnText = this.value;
track(this, eventType, '', '', ctrBtnText, '', '', '');
}
Reason to use preventDefault:
function validateForm(e) {
var data = document.getElementById('someData').value;
if (isValid(data) === false) {
e.preventDefault();
// ask user to correct invalid data here
}
}
Note: you can submit forms manually with this.form.submit()
but this is usually not needed as the default action does this for us.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.