简体   繁体   中英

Prevent parent script from firing

I have a DotNetNuke website. Baked into the DNN code is the following script

<script type="text/javascript">
//<![CDATA[
function WebForm_OnSubmit() {
    dnn.controls.submitComp.onsubmit();
    return true;
}
//]]>
</script>

The problem is, I put a form on a page on my website that performs a search, and I wired up a jquery listener that says if the enter key is pushed, fire my button click event. The problem is, the parent script above ALSO fires that WebForm_OnSubmit() function, and whatever that onsubmit() function\\return true does is causing my page to just refresh.

So, if there anything i can do so "override" or "prevent" that WebForm_OnSubmit() function from also triggering?


Edit 1: In response to the question "how is your listener setup":

I have a function called canISearch:

function canISearch() {
    if (event.keyCode == 13) {
        event.stopPropagation();
        $("#btnSearch").click();
    }
}

and I fire this function using my onkeydown attribute:

<input type="text" id="txtblah" onkeydown="canISearch()" />

If WebForm_OnSubmit is in the global space, you can overwrite it and create an exception for your case. Sometime after the original function is defined, redefine it. Maybe something like this:

(NOTE: updated to incorporate information from Samy's answer below)

(function () {
    var originalFn = dnn.controls.submitComp.onsubmit;
    dnn.controls.submitComp.onsubmit = function() {
        if ([your element is in focus]) {
            ... do your thing ...
        } else {
            originalFn();
        }
    };
})()

How is your listener set up? You should be able to stop propagation of the event to keep it from moving up the event hierarchy:

$(".element").keyup(function(e){
    e.stopPropagation();
});

You could either monkey patch the dnn code in order for the method to do nothing when your function is present on the page:

dnn.controls.submitComp.onsubmit = function() {/*doing nothing, ladida*/};

Which may be a bit harsh since your modification can have an impact on other behaviors. You can instead add a method that checks that your control has focus before routing the code accordingly. This is most likely the simplest hack.

You could also prevent the event from bubbling up, as Brennan suggests; it really depends how events are attached. If I remember correctly DNN can intrude on your events in so many ways this may not be easy to do.

Or you could create your own skin in order to control all the components that are pushed onto the page and prevent the auto submit from the wrapping form.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM