1

I need to attach a submit listener to every form in an iframe but I can't use jQuery.

What's the best way of doing this? I'd rather not use window.onload because that requires waiting until the images have loaded which may take time. Obviously, $(document).ready() would have been perfect, but as I said, I can't use jQuery for this.

Thanks

Nick Brunt
  • 9,533
  • 10
  • 54
  • 83

2 Answers2

4

Onload will do the trick. Martin's jQuery approach will be maybe faster.

for(var i=0; i<document.forms.length; i++){
  var form = document.forms[i];
  form.addEventListener("submit", myListener,false);
}
Jan Pfeifer
  • 2,854
  • 25
  • 35
  • Well you've both answered a different part of the question perfectly, which do I accept?! – Nick Brunt Sep 22 '11 at 12:16
  • Well, its up to you. I have answered your primary question. Accept the one which helped you most. – Jan Pfeifer Sep 22 '11 at 12:38
  • Wow that's is perfect answer. after 20 mins of research I found solution for handle submit event Listener for multiple form in same Page without id. Thanks – Harsh Patel Feb 04 '22 at 02:21
1

Just roll your own :) here is the code that jQuery uses to have the ready event, take what you need, it's free (but do mention in your code where it came from ;)

bindReady: function() {
        if ( readyList ) {
            return;
        }

        readyList = jQuery._Deferred();

        // Catch cases where $(document).ready() is called after the
        // browser event has already occurred.
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            return setTimeout( jQuery.ready, 1 );
        }

        // Mozilla, Opera and webkit nightlies currently support this event
        if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, false );

        // If IE event model is used
        } else if ( document.attachEvent ) {
            // ensure firing before onload,
            // maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", DOMContentLoaded );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", jQuery.ready );

            // If IE and not a frame
            // continually check to see if the document is ready
            var toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) {}

            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }
    },
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68