William Tuttle William Tuttle - 1 month ago 9
Javascript Question

JS Appending string as function parameter is giving a weird output

I have a function that creates and "a" tag and appends it a div using Jquery's .innerHTML function. Im trying to define the function onclick will call and pass a string as it's parameter. However, when running the code the string changes, white space is replaced with this ( =" "). Which is strange because the same string is used elsewhere in the tag and is printed correctly. Here's my code:

var companies = companyString.split(",");
var dropDown = document.getElementById('myDropdown');

for (var item in companies){
var str = "World Wrestling Entertainment"; //example

dropDown.innerHTML = dropDown.innerHTML + "<a href='#' onclick='filterCompany('"+str+"')'>"+str+"</a>";
}


any ideas?

thanks

this gets spit out in html as:

<a href="#" onclick="filterCompany(" world="" wrestling="" entertainment')'="">World Wrestling Entertainment</a>

Answer

You've just muddled the quotation marks a bit.

If you don't want to deal with escaping quotes, try doing it this way:

var companies = companyString.split(",");
var dropDown = document.getElementById('myDropdown');

for (var item in companies){
    var str = "World Wrestling Entertainment";  //example

var on_click - 'filterCompany('+str+')';

dropDown.innerHTML += '<a href="#" onclick="'+on_click+'">'+str+'</a>';
Comments