Using JavaScript to modify a section of an anchor link attribute

I am looking to dynamically update part of the URL when a specific radio button is selected.

There are three purchase links, each representing a different amount. After choosing an animal, I need to select one of the three amounts to spend. How can I modify a portion of all three URLs simultaneously?

To achieve this, I have implemented radio buttons using 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>

Here are the purchase links corresponding to $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 section marked with DOL is the only portion that requires modification.

Answer №1

To ensure the Id's on your buttons are unique, create a function like this:

<script type="text/javascript>
    function updateLinks(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>

Then, include this code in your radio buttons:

onclick="updateLinks(this);"

Answer №2

onclick="document.getElementById('editBTN').href='http://example.com/eventInfo?ticket='+this.value;"

Answer №3

When you're dealing with strings in programming, regular expressions can be a powerful tool for manipulating the text to suit your needs. In this case, trimming away unwanted parts of the string is as simple as using the right regular expression:

var btnID = getElementById('myBtn');
btnID.setAttribute('href', newURL);

Answer №4

By utilizing jQuery or a different DOM parsing library, achieving this task should be feasible.

if ( /* condition for radio selected */ ) {

    // Retrieve the src attribute
    var src = jQuery( 'selectorforanchortag' ).attr('src');
    // Modify the src using JavaScript string methods
    src = src.blergetyblerg();
    // Set the new src in place of the original
    jQuery( 'selectorforanchortag' ).attr('src');

}

Answer №5

click event to change the URL of an element with the ID 'editBTN':

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing the Slider Range with HTML DOM Style's BackgroundImage Attribute

I have a slider range that I'd like to modify using JavaScript. Specifically, I want to change its background-image property. To achieve this, I attempted the following script: document.getElementById("range").style.backgroundImage = "linear-gradient ...

What is the best way to manage undefined status in react after the user chooses to cancel selecting a file?

Having an issue with my simple Input file type in React. I'm storing the selected file in state, but when I click the clear button, the state doesn't actually get cleared. This leads to {selectedFile.name} throwing an undefined error if the user ...

Having difficulty inserting an image with style="background-image:url(' ')" in Rails from the database

Hi everyone! I am new to both Rails and Stack Overflow, and I would really appreciate it if someone could guide me here. I am currently working on a test site that resembles a personal blog. It's mainly for showcasing one user's portfolio. In t ...

Loop proceeding without waiting for promise resolution containing nested Firebase call

I am currently facing an issue with making Firebase database calls within a loop and an outer Firebase call. The inner database call utilizes data returned from the outer call and the loop, hence it is nested inside the outer one. The goal is to set the re ...

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

Configuring Jest unit testing with Quasar-Framework version 0.15

Previously, my Jest tests were functioning properly with Quasar version 0.14. Currently, some simple tests and all snapshot-tests are passing but I am encountering issues with certain tests, resulting in the following errors: console.error node_modules/vu ...

Creating a responsive single webpage using HTML/CSS

How can I make some div or img responsive for mobile format? <meta name="viewport" content="width=device-width, initial-scale=1" /> <div class="container"> <h1 class="title"> ...

Issue with Flex display not being applied within Material UI Grid Item

I am attempting to position an element at the end of a Grid Item (horizontally). In order to achieve this, I am enclosing my component in the following div: Here is the complete code snippet: <Grid container spacing={8} alignItems={'stretch' ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

The synergy between ES6 arrow functions and array mapping techniques

I'm currently exploring shorthand methods of writing ES6 code and I've come across an example that has left me puzzled. The last shorthand used, "({length})", retrieves the length property of an array. While I understand how it works in this cont ...

How to choose between GET/POST and USE in ExpressJS for URL filtering

router.get('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) VS router.use('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) Could someon ...

Using React.js to select and change the color of an element

I'm developing a movie theater app, in which I am building a feature to select seats in the cinema hall and add them to the cart. Here is the function that displays the cinema hall: export default function CinemaHall(props) { const row = props.row ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

Tips for storing the output of a script URL in a JavaScript variable

I am currently facing an issue with running a script in the 'head' element of a webpage. The script makes an API call to a specific URL and retrieves results in the form of a JavaScript array. However, I am encountering difficulty because the API ...

An error occurred when attempting to use the getDoc() function from Firebase within Next.js: TypeError - reading 'map' on properties of undefined

Hello everyone at StackOverflow, I ran into a problem while attempting to use .map() on a getDoc() constant in my Next.js application. The error message I'm getting is: "TypeError: Cannot read properties of undefined (reading 'map')". As a n ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Seeking assistance with formatting output for OpenCPU and igraph

Here is my adjacency array data: var g = [[10, 2], [15, 0], [18, 3], [19, 6], [20, 8.5], [25, 10], [30, 9], [35, 8], [40, 5], [45, 6], [50, 2.5]] The code I am using in OpenCPU is as follows: ocpu.call("centralization.closeness", {graph: g} ...

Get the PDF file and access it with Ajax technology

I am facing an issue with my action class that is responsible for generating a PDF. The code snippet shown sets the contentType appropriately. public class MyAction extends ActionSupport { public String execute() { ... ... File report = si ...

Obtain data with matching JSON values in a REACT application

Recently, I received a JSON file that looks something like this: [ { "symbol": "A", "name": "Agilent Technologies Inc", "exchange": "NYSE", }, { "symbol": "AAC ...