0

I'm trying to create a link which has a dynamic value in it

http://my.link/index.php?action=huh&id=X

The X is what i want to replace dynamically with javascript variable. I don't want to use jquery for it.

AND, i do not want to replace the whole url(href) because some part of URL needs to parsed by the template engine. I think it'd be better if i inserted an element in place of X and replaced it with JS

2
  • Do your anchors with a dynamic href have a class? Is this not contained in an anchor? Yes, it can be done in Javascript but we need more info on your implementation. Commented Jul 24, 2012 at 16:28
  • yes. It does have a class. I edited my question to make it easier to understand Commented Jul 24, 2012 at 16:30

2 Answers 2

1

only replace id

var elLink = document.getElementById("link");
elLink.href = elLink.href.replace(/id=(.*)/, function(){return "id=2"});

if id=X is constant

elLink.href = elLink.href.replace("id=X", "id=2");
Sign up to request clarification or add additional context in comments.

2 Comments

That worked like charm. but it removes the rest of my URL. This is my full URL: http://my.link/index.php?action=huh&id=X&k={$template_engine_stuff} ..... after applying your code, the result is : http://my.link/index.php?action=huh&id=2 Is there a workaround for this?
damn. I feel like an idiot. It works perfectly now You sir, are my hero
0

You can use something like

document.getElementById("YourAnchorId").href= document.getElementById("YourAnchorId").href + id;

or

document.getElementById("YourAnchorId").href= document.getElementById("YourAnchorId").href +"?id" + id;

And that id variable get it from a textbox or however you need it.

And whats its the reason for not using jquery?

2 Comments

well, i do not want to replace the whole href because (as i stated in my post), some part of the url needs to by parsed by the template engine And i don't want to use jquery because 1. it conflicts with my prototype 2. i don't want to add unnecessary 89KB
I'd try that. But i already got a working solution. thanks for giving your time tho

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.