Carlos Siles
Carlos Siles

Reputation: 71

Append values into an existing anchor href

I have captured 3 values from a datalist template using JavaScript, now I need to append these values into an existing anchor which is:

<a id="link" href='nextpage.aspx?id=<%#Eval("PlateId")%>&pp= #Eval("price")%>'>

I found the way to get the anchor href from JavaScript:

<script language='javascript' type="text/javascript" >
    function addLink() { 
        var anchor = document.getElementById("link"); 
        anchor.href = anchor + "&qty=";} 
</script>

But, I can't add the js value after "&qty=", I have tried adding the value like this:

anchor.href = anchor +"&qty=+Value+"

And with this:

anchor.href = anchor +"&qty='Value' "

I can't put it out of the quotation marks, because it won't display in the anchor.

Upvotes: 5

Views: 8725

Answers (2)

venkatskpi
venkatskpi

Reputation: 820

Dynamically change <a href=""></a> href atrribute value (or) You can able to append the existing URL

Tips: 1 - Use the jQuery .attr() Method

 $("selector").attr("href", newURL));

Tips: 2 - Use javascript element selector document.getElementById

example:

<a href="test.php" id="test">TEST URL</a>
var redirect_url = document.getElementById('test');
redirect_url.href = "new url";

(or)

document.getElementById('test').href = "newURL";

(or)

using setAttribute() method *Note:broken in IE

redirect_url.setAttribute("href", "new url");

Upvotes: 0

Barney
Barney

Reputation: 16456

anchor.href = anchor + "&qty="

should be

anchor.href = anchor.href + "&qty="

...otherwise you are trying to turn the link element into a string!

Meanwhile, you still need to keep Value out of the quotation marks, otherwise the final text generated will always be exactly that text: Value. If Value is a variable and is not returning the value you expect (an empty or undefined value, for example), then you need to look at the code that declares it and change that.

Upvotes: 4

Related Questions