I have a JavaScript function within a JavaScript function. The JavaScript below inserts some HTML in a div using getElementbyID.
It is passing one variable okay–that seems to be a child of an object, this.value–btw, I am a JavaScript newb, however, when I try to give it another variable to pass, the string represented by l it stops working. Below type 1 which tries to pass variable l does not work, else, does. I have also just tried putting l '+ but that did not work. Can anyone help me with proper syntax for passing variables?. Thank you.
if (type==1)
{
var mailbox = '<form action="mail.php" method="post"><input type="text" onkeyup="showResult(this.value,'+l+')"><input type="submit" name="submit" value="Email"><div id="livesearch"></div></form>';
}
else
{
var mailbox = '<form action="share.php" method="post"><input type="text" onkeyup="showResult(this.value)"> Share<div id="livesearch"></div></form>';
}
document.getElementById(target).innerHTML = mailbox;
return false;
}
If the string contains
"Check this out."with the double quotes, this is what the resulting HTML markup would look like (with formatting added):Note how the attribute value for
onkeyupcontains a", which would close out the attribute, resulting in invalid HTML. If the string containsCheck this out.without any quotes, the end result is still invalid, for another reason:In this case,
showResult(this.value,Check this out.)is the event handler JavaScript, and that has a syntax error. What you want is for the string to be in single quotes so it doesn’t break the attribute and so it’s valid JavaScript:Note that it is not recommended to attach events in this way because it’s so easy to make this type of mistake. Rather, assign an event handler to the DOM element, not HTML: