Search code examples
javascripthtmlhref

Change part of an anchor link attribute with JavaScript


I'm trying to change the middle part of the URL when the proper radio button is clicked.

In the three purchase links each one represents an amount. I'm going to be selecting an animal then clicking on 1 of 3 amounts I want to spend. How would I change part of all 3 of the URLs?

How could I go about doing that? These are the radio buttons (with JavaScript):

<input type="radio" name="orderID" 
    value="-DOL&linkID=naib&url=https%3A//example.com/List%3FlinkID%3Dnaib"
    onclick="document.getElementById('editBTN').href=this.value">
    Dolphin
</input>
<input type="radio" name="orderID" 
    value="-SHK&linkID=naib&url=https%3A//example.com/List%3FlinkID%3Dnaib"
    onclick="document.getElementById('editBTN').href=""+this.value">
    Shark
</input>

And the purchase links (250$, 100$ and 50$, respectively):

<a id="editBTN" href="http://example.com/Info?ticketCode=%XX%3A%Q250">Purchase</a>
<a id="editBTN" href="http://example.com/Info?ticketCode=%XX%3A%Q100">Purchase</a>
<a id="editBTN" href="http://example.com/Info?ticketCode=%XX%3A%Q50">Purchase</a>

The DOL part is the only part that needs to change.


Solution

  • If you're going to rename the Id's on your buttons to be unique, make a function:

    <script type="text/javascript">
        function setAnimal(obj) {
            var baseURL="http://ev8.evenue.net/cgi-bin/ncommerce3/SEGetEventInfo?ticketCode=%3ANAIB%3A%3AAQ";
            document.getElementById('editBTN1').href=baseURL+"250&"+obj.value;
            document.getElementById('editBTN2').href=baseURL+"100&"+obj.value;
            document.getElementById('editBTN3').href=baseURL+"50&"+obj.value;
        }
    </script>
    

    and then, on the radio buttons do:

    onclick="setAnimal(this);"