Search code examples
javascriptjquerynew-window

How to open multiple windows with jQuery/js and trigger a form submit event?


Given a comma-separated string of URLs, I want to open a separate window for each element of its converted-to array, then submit a form.

The following code only opens one window, and no form submit takes place:

$.each(urlList.split(","), function (index, item) {

    urlList = "http://www.cnn.com,http://www.foxnews.com";

    _gaq.push(['_trackEvent', 'Results', 'Click', 'Classifieds+: ' + item + ' : ' + SourceUrlProviderID]);
    window.open(item, "_blank");
});
document.forms[0].submit();

When I do the following, I get the desired action - three new tabs/windows open, but I it looks like the form submit would be done twice and doesn't quite make sense:

urlList = "http://www.cnn.com,http://www.foxnews.com";

// opens windows for each URL in the string
$.each(urlList.split(","), function (index, item) {
    _gaq.push(['_trackEvent', 'Results', 'Click', 'Classifieds+: ' + item + ' : ' + SourceUrlProviderID]);
    document.forms[0].submit();
    window.open(item, "_blank");
});

Can someone shed some light on this please?


Solution

  • Why urlList is inside $.each? Anyway, I tried this, and works:

    var urlList = "http://www.cnn.com,http://www.foxnews.com"
    $.each( urlList.split( "," ), function( index, item ) {
        window.open( item, "_blank" )
    });
    document.forms[0].submit()