I have a tampermonkey script where I'm trying to take an array of names, and for each one perform a search and print the page. It runs automatically when you load the page, which is why the if
statement is necessary.
$(document).ready(function(){
var searchBar = $('input[name="searchfield"]');
var submit = $('button[name="searchbyname"]');
if ( searchBar.val() < 1 ) {
var namesArray = prompt('enter names to search, separated by commas').split(', ');
$.each(namesArray, function(i, v) {
$(searchBar).val(v);
$(submit).trigger('click');
window.print();
});
}
})
My problem is that it is only running the $(submit).trigger('click');
on the last loop through. So if my array is 'one, two, three' it will enter 'one' into the search bar, replace it with 'two,' then 'three,' and only then will it actually trigger the search button.
(This answer is in response to what I perceive as the real need, "How can I use Javascript to automatically print search results from a series of HTTP search queries?", in good faith that the poster will tweak the question accordingly.)
You are actually trying to use Javascript to print search results from different pages. Your approach will not work for this purpose (and therefore the original question of
$.each
looping is invalid); every time the search is submitted, your Javascript runtime and userscripts are nuked.To accomplish the end goal, you need to separate the query loop from the window that submits the HTTP request. The trick: create an iframe containing this website, then control that iframe from the
top
window.Here's code that could be copied into the developer console directly. I've only tested it with the console, but it should be adaptable for script injectors like Tampermonkey.
Note that the parts designed specifically for your use case are
fieldname
andformname
at the top. The rest of this is completely generic; you could use with any website that has appropriatename
attributes on theinput
andform
elements.