How to Prevent Bubbling For Form Submit

╄→尐↘猪︶ㄣ 提交于 2020-01-16 00:36:30

问题


I have form that calls the function GenerateWords when it is submitted and returns false.

<form id="3Form" onsubmit="GenerateWords(this); return false;">

This is causing problems with Google Tag Manager implementation as it does not bubble up to the form submit listener.

I understand event.preventDefault(); needs to be used and return false removed but don't know how to implement this. The current javascript I have is:

function GenerateWords(F) {
var strWords = F.words.value;
if ... condition is false
    return false;
}
if ... condition is false
    return false;
}
vars declared
for (var i = 0; i < ctLines; i++) {
    var strLine = arrLines[i];
    strLine = Trim(strLine.replace(/[\r]/g,""));
    if successful condition
    }
}
F.result.value = oResult.join("");
F.result.focus();
}

Any help would be appreciated. Thanks.


回答1:


Try this in javascript:

 function GenerateWords(F,ev) {  // event object 
    ...
    if(someCondition)  // condition when the form should not be submitted.
    ev.preventDefault();
    }

and you may remove return false; from the form tag and pass the event reference

<form id="3Form" onsubmit="GenerateWords(this,event);">


来源:https://stackoverflow.com/questions/25092840/how-to-prevent-bubbling-for-form-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!