0

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?

ElHaix
  • 12,846
  • 27
  • 115
  • 203

2 Answers2

2

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()
Chris
  • 1,264
  • 1
  • 10
  • 14
  • Thanks for the urlList catch... should have been *item*. Tried that code, and still only one window opens. With the document.forms[0].submit in the loop before the window.open, it works fine - three windows appear. The third windows is opened by the submit(). – ElHaix Feb 01 '13 at 20:26
  • What do you mean the "should have been item"? Please update your code to correct one. – Chris Feb 01 '13 at 20:31
0

you should submit the form just out of the loop (each in this case) if you cannot do that just check if it is the last item.

if (index == urlList.split(",").length)
   document.forms[0].submit();

but to be honest this does not look like a correct way to do. Why you are submitting the form if just for the stats you can use a simple AJAX call.

Onur Topal
  • 3,042
  • 1
  • 24
  • 41
  • The code started out with a Razor MVC3 form post request, where the parameters are read by the controller. Trying to not re-wire the whole thing. – ElHaix Feb 01 '13 at 19:22
  • you can submit the code by jQuery ajax post http://stackoverflow.com/questions/5004233/jquery-ajax-post-example – Onur Topal Feb 02 '13 at 12:45