jquery script that retrieves the href attribute of the anchor tag located near the button that is currently being clicked

Hello there!

I am trying to extract the href of a link when the button next to it is clicked by the user. However, the challenge is that there are multiple buttons and links on the page. For example, if the first button is clicked, I want to display "www.a.com", and if the 3rd button is clicked, I want to display "www.c.com". Can anyone guide me on how to achieve this seamlessly? Thanks in advance!

<div>
<a href='www.a.com'>a</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.b.com'>b</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.c.com'>c</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>
<div>
<a href='www.d.com'>d</a><input type='button' class='btn' onClick='validate()' value='V'/>
</div>

<script type="text/javascript">
function validate()
{
alert($('div a').closest('a').attr('href'));
}
</script>

Answer №1

Experiment using parent and child in this way

function validate()
{
    alert($(this).parent('div').child('a').attr('href'));
}

You could also retrieve it using prev like

alert($(this).prev('a').attr('href'));

Answer №2

Perhaps it would be better if I implemented it like this:

$(document).on("click",".btn",function(){
  alert($(this).prev('a').attr('href'));
});

It seems that with this code, the onclick event is not necessary.

Answer №3

try:

function checkValidity()
{
   displayMessage($(this).siblings('a').attr('href'));
}

Answer №4

attempt

 $(document).ready(function () {
        $(".button").click(function () {
            alert($(this).parent().children("link").attr("src"));
        });

    });

Answer №5

Eliminate the onClick='validate()' event from every button element and experiment with the provided code snippet below:

  $('.btn').click(function () {

        alert($(this).prev().attr("href"));
    });

Answer №6

To access the previous element in the event source, use `prev()` and pass the source object to the function

Check out the live demo here

HTML

onClick='validate(this)'

JavaScript

function validate(obj)
{
   alert($(obj).prev('a').attr('href'));
}

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

Guide on implementing event listener for right click using pure JavaScript (VANILLA JS)

I need the div to appear wherever the cursor is holding down the right mouse button. In my scenario, I am using the following code: <div class="d-none" id="item"></div> #item{ position: absolute; top: 0; left: 0; w ...

Keep the music playing by turning the page and using Amplitude.js to continue the song

I have implemented Amplitude.js to play dynamic songs using a server-side php script. My objective is to determine if a song is currently playing, and if so, before navigating away from the page, save the song's index and current position (in percenta ...

What is the best way to handle waiting for an HTTP request to complete from a separate component?

https://i.sstatic.net/q4XYB.png An issue arises when calling the GetData function from a component's controller too early. I would like it to wait for the identification process to complete before triggering. During page loading, there is a server c ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Utilize either the success() or complete() method when making an AJAX call

Can someone please explain the AJAX call below, specifically focusing on the complete() method? I've noticed that replacing complete() with success() results in an empty responseText, similar to when using the AJAX error() method. However, if I keep ...

NetBeans is unable to analyze javascript files that are considered "large" (over 350 KB)

I have a significant JavaScript file (approximately 6 MB) that includes library API and documentation as shown below: /** * Function doc */ library.class.func=function(something){}; /** * Function 2 doc */ library.class.func2=function(something){}; ...

Keep an ear out for upcoming occasions once the transition has been completed

I am looking to create a smooth transition effect that will push the main content downwards when the Twitter Bootstrap collapse menu is activated using the toggle button. However, I have noticed an issue where if I quickly double click the toggle button, ...

Is it possible to establish a limit on a field's value in MongoDB?

Just a quick query - I'm curious if there's a feature in mongodb that allows for fields to have a set maximum value. For instance, let's say the field "cards" is restricted to a maximum value of 100. If an increment would exceed this limit, ...

Discover the element's selector for the event that was triggered using jQuery

In the process of creating a lightweight real-time application, we are utilizing jQuery's event system to facilitate communication between modules. Any changes made in the DOM that affect elements outside the module are achieved through triggering eve ...

Error message: jQuery DataTables encountering issues with POST Server Side JSON communications

My table is not loading correctly via ajax. Here is the JavaScript code I am using: $('#initAjaxDataTable').DataTable( { "pagingType": "full_numbers", "processing": true, "serverSide": true, "ajax": { "url": $('#ini ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

What is the most efficient way to utilize a single Google Data Studio template across multiple accounts in a dynamic manner

I've been exploring different options on how to accomplish this: My dataset contains information on various clients, and I am interested in designing a custom Google Data Studio template for specific reports. Ideally, I would like the template to be ...

How to programmatically submit a file using jQuery

Is there a way to automatically submit a form to a php file using jQuery? Currently, I have the following form setup: <form action='add.php' method='get'> <input type='hidden' name='title' value='$ ...

What is causing my Bootstrap Controls to malfunction?

I'm trying to create a Bootstrap carousel that shows 3 items at once and includes controls to switch between them. The carousel I've made does display the three items, but for some reason, the controls are not responding when clicked. I'm un ...

Tips for accessing information from an Angular Resource promise

I am currently facing an issue when trying to read data from an angular promise that was returned. Before, I had the following code: var data = category.get({id:userid}); Later, I realized that the data being returned was an unresolved promise. So, I ma ...

Transforming jquery code into angularjsAre you looking to migrate your

I am currently struggling with converting a jQuery function into an AngularJS function. Here is the specific code snippet: $('p').each(function() { $(this).html($(this).text().split(/([\.\?!])(?= )/).map( function(v){return '< ...

Unusual behavior of the `map` function in Firefox's JavaScript

Here's an interesting observation regarding the behavior of the map function in Firefox. In a particular error scenario on a web application, when Firebug pauses at the error, entering the following code into the Firebug console: ["a", "b", "c", "d" ...

Step-by-step guide to implementing a user-friendly search input field using the powerful AngularJS material design framework

I am searching for an effortless method to implement a feature similar to the expandable search text field in angular-mdl. By clicking on a search button, it will expand into a text field. <!-- Expandable Textfield --> <form action="#"> < ...

personalized options for initiating and concluding html audio component

I am currently facing an issue with my html audio element that plays a track. The setup is quite straightforward: <audio controls loop="loop"> <source type="audio/wav" src="song.wav"> </audio> However, I need to create custom start ...

I'm encountering a type error stating that children are not defined when attempting to establish parent-child relationships from a flat array. What

Trying to establish a parent-child relationship between modules based on their IDs. Ran into an issue with the function I used, as it returned an error stating that children were not defined. const data = [ { module_id: "96ac027b-b5ce-4326-b5db- ...