I am writing a script that will show in two columns a list of suggested words on a website page. A given suggested word will display as a hyperlink that will go to another page with more information about that specific word. The problem I am having is that the hyperlink is only showing the first word in the suggested word at that place in the array. For example, if the suggested word at suggestions[m] was supposed to be "dog house", the hyperlink only has "dog" and thus goes to the wrong other page with more information. The displayed word is correct, so it shows "dog house" on the page, it is just the hyperlink that is incorrect. What am I doing wrong with the href? Is there something about the template that prevents multiword strings?
if(suggestions.length) {
var table = '<table cellspacing="1" cellpadding="5">';
var tolength = suggestions.length
if (tolength ===1){
for (var i = 0; i < suggestions.length; i++) {
var b = suggestions[i]
table += '<tr>';
table += '<td><a href=word?word=>' + suggestions[i] + '</a></td>';
table += '</tr>';
}
}
if(tolength > 1){
for (var m = 0; m < tolength; m+=2) {
table += '<tr>';
table += '<td><a href=word?word='+ suggestions[m] + '>' + suggestions[m] + '</a></td>';
table += '<td><a href=word?word='+ suggestions[m+1] +'>' + suggestions[m+1] + '</a></td>';
table += '</tr>'
}
}
table += '</table>';
document.getElementById('sug').innerHTML = table;
}
2
Answers
your issue is the spaces in the string need to be encoded to %20 . Wrap your suggestions[m] in encodeURIComponent() this will result in a string like "dog%20house"
https://www.w3schools.com/tags/ref_urlencode.ASP
You missing double quotes, try this code below