I would like to create JS code that put next elements from array in form after some action, for example after click.
I want to run this code in console (firebug, firefox F12) while im visiting some website. I created test example of code that should work on stackoverflow but it doesn't, why?
Example - stackoverflow.com:
After clicking in header area (id #question-header), my next element from array should be displayed in search form input (name q).
Code doesnt work when I run it in firefox console.
var arr = ['foo', 'bar', 'baz'];
var i = 0;
function nextItem() {
i = i + 1; // increase i by one
i = i % arr.length; // if we've gone too high, start from `0` again
return arr[i]; // give us back the item of where we are now
}
window.addEventListener('load', function () {
document.getElementsByName('q').value = arr[0]; // initial value
document.getElementById('question-header').addEventListener(
'click', // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementsByName('q').value = nextItem();
}
);
});
How I can fix it?
#search?#search? is itdiv,spanorinput?qisinput,searchisform.. butinputstill not workingnextItemcould bereturn arr[++i % arr.length];