Dynamically Creating Links With JavaScript

Recently asked on Yahoo! Answers:

Javascript syntax question to get php passed?

submenuItem("Februa# ry-07",loc+"index.php?m=2&y=2007","","x2... 007_plain");

this is a line from my javascript for a drop down menu. I added two “# ” in the line just so yahoo wouldnt truncate it. The problem that i am having is that the menu works, but when i go to test it and hit a hyperlink from the submenu it chops everything to the right of the ? so i just get index.php . When i just remove the question mark, i get

index.phpm=2&y=2007

so i have determined that the question mark in the ahref is causing the problem. Im not too familiar with javascript syntax, is there something that i can do so i can get

index.php?m=2&y=2007

thanks

Additional Details

function submenuItem(text,url,tar,s){

if(NS4)return;
if(text.charAt(0)=='<')
d.write(text);
else if(text=="---")
d.write("<div class=\""+s+"\" style=\"width:"+menuw+"px\"><center><img src=\""+loc+"---.gif\" height=\"8\" width=\""+(menuw-6-(2*bd))+"\" border=0/></center></div>");
else{
d.write("<a ");
if(url!="")
d.write("href=\""+url+"\" ");
if(tar!="")
d.write("target=\""+tar+"\" ");
d.write("class=\""+s+"\" style=\"width:"+menuw+"px\"> "+text+" </...
}
}

this is the function

There’s no problem with using a question mark in JavaScript. Your syntax has some issues and the way you’re outputting your script is not paticularly sound, which is causing your problems. Also, you should convert your ampersands to entities.

To demonstrate, make an HTML page with the following DIV in the body:

Next, add this JavaScript function to the page:

function makeLink() {
	var mydiv = document.getElementById("test");
	var out = 'Dynamic Link';
	mydiv.innerHTML = out;
}

Change your body tag to this:


Run that test page. You’ll notice that there is now a link in the DIV, which links to test.php?m=2&y=2007.

Comments Closed

Comments are closed for this post. If you have questions, would like assistance, or otherwise would like to discuss this post, please contact me directly.