I have the following on a web page:
<td class="containslink" id=1>
<a href=/ControllerX/ActionY/7>View</a>
</td>
There are many versions of the above, each with a different id.
When the included link is clicked, I need the page to fire an AJAX call to the following address:
/Controller/Action/1
or
@Url.Action("Action", "Controller" new { id = 1 })
Where id is equal to the td‘s id.
If I hardcode my AJAX call like this:
myUrl = @Url.Action("Action", "Controller" new { id = 1});
$(document).ready(function () {
$("a").click(function(){
$.ajax({
url: myUrl,
});
});
});
The AJAX call fires when I click any link on the page and always fires with the id of 1 (obviously).
How would I change this AJAX call so that it only works when I click on a link contained within a td class of "containsLink", and includes the id of the td that contains the link that was clicked?
You’d need to tighten your selector (don’t just select all
<a>elements) and get the ID in the event handler.Note that
1is an invalid ID as it starts with a number. You might want to usedata-attributes instead, likedata-id.