Reputation: 33
I want to build my own "keyword shuffler" (eg. for Google Ads). For this I have created an HTML5 document with two input fields and one output field.
The idea is: You can write an arbitrary number of words (separated by comma) into each of the input fields. Then, if you click on a button, the output-field shows all possible combinations (pairs) of the two input-fields, with the condition, that the first word comes from 'input1' and the second word from 'input2'.
Additionally: I want to manipulate the output rows (eg. add some characters, such as '' or + or [] ), but this can be another question:)
I can already extract the inputs and convert them into two arrays. To combine them, I have made a nested 'for .. of' function. In my console.log i can already see all the results, but in my 'output'-field there is only the last combination.
function keywordShuffler(){
var kw1_array = ['keywordA','keywordB','keywordC']; // an abritrary number of keywords
var kw2_array = ['keyword1','keyword2','keyword3','keyword4']; // an abritrary number of keywords
for (value of kw1_array){
for (value2 of kw2_array) {
var output = value + ' ' + value2;
document.getElementById("output").value = output;
console.log(output); // to test the output
}
}
}
My expected output:
keywordA keyword1
keywordA keyword2
keywordA keyword3
keywordA keyword4
keywordB keyword1
keywordB keyword2
keywordB keyword3
keywordB keyword4
keywordC keyword1
keywordC keyword2
keywordC keyword3
keywordC keyword4
what I get:
keywordC keyword4
Upvotes: 3
Views: 134
Reputation: 3010
function keywordShuffler(){
var kw1_array = ['keywordA','keywordB','keywordC'];
var kw2_array = ['keyword1','keyword2','keyword3','keyword4'];
for (value of kw1_array){
for (value2 of kw2_array) {
var output = value + ' ' + value2 + '<br>';
document.getElementById("outputs").innerHTML += output;
console.log(output);
}
}
}
<button onclick="keywordShuffler()">click me to check</button>
<span><div id="outputs"> outputs....</div></span>
Upvotes: 0
Reputation: 780974
You need to concatenate the value from each iteration. You can assign to the output element at the end of the loop.
function keywordShuffler() {
var kw1_array = ['keywordA', 'keywordB', 'keywordC']; // an abritrary number of keywords
var kw2_array = ['keyword1', 'keyword2', 'keyword3', 'keyword4']; // an abritrary number of keywords
var output = '';
for (value of kw1_array) {
for (value2 of kw2_array) {
output += value + ' ' + value2 + '\n';
document.getElementById("output").value = output;
}
}
}
keywordShuffler();
<textarea id="output" rows="10"></textarea>
Upvotes: 0
Reputation: 345
Try appending the output to an element other than replacing previous value with new value.
document.getElementById("output").value += output;
Upvotes: 3