How to get the clicked element's ID - javascript

I want to retrieve the ID of the clicked element (on the 'onclick; event.
<script>
function myFunction(element)
{
var $id = element.id;
$($id).click(function() {
$.get('ajaxTestSrvlt?test=1', function(responseText) {
$('#firstName').val(responseText); with the response text.
});
});
};
</script>
This is the element this function was called upon. I would like to get the ID of this raw from the above script. This only works when I directly give the "clickableRow" as to id to the Script. The "ID" is to be changed dynamically
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal" onclick="myFunction(this)">

There is no need to have a inline event handler
<tr id="clickableRow" style="cursor: pointer;" class='clickable-row' data-href="#" data-toggle="modal" data-target="#editModal">
then
jQuery(function () {
$('.clickable-row').click(function () {
var $this = $(this),
id = this.id;
$.get('ajaxTestSrvlt?test=1', function (responseText) {
$('#firstName').val(responseText);
//here `id` is the id of the clicked tr
});
});
})

Try this
function myFunction(ele)
{
var id=$(ele).attr("id");
$('#'+id).click(function() {
//code here
});
}

Simply use this
onclick="myFunction(this.id)
Instead of
onclick="myFunction(this)
Get your id on my function
function myFunction(getid) {
alert(getid);
}

Related

Button within modal's table not firing [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
Attempted to put a delete button that works in a table into a modal, with a table and it's like the click event is not firing at all. Hit's not back end code, no console.log(s), or js break points. Am I missing something?
Modal's Table
<table class="table table-hover table-md ">
<thead>
<tr>
<td class="text-left TableHead">Role</td>
<td class="text-right TableHead">Delete</td>
</tr>
</thead>
#*--Table Body For Each to pull DB records--*#
<tbody>
#foreach (var role in Model.Roles)
{
<tr>
<td>#role</td>
<td>
<button class="sqButton btnRed float-right zIndex"
title="Delete" data-toggle="ajax-modal" data-target="#deleteRoleUser"
data-url="#Url.Action("Delete", "Administration",
new {Id = Model.Id , Type = "roleUser"})" >
<i class="glyphicon glyphicon-remove"></i>
</button>
</td>
</tr>
}
</tbody>
</table>
Controller that it's supposed to call
[HttpGet]
public async Task<IActionResult> Delete(string id, string type)
{
if (type == "user") {
ViewBag.Type = "user";
var user = await userManager.FindByIdAsync(id);
if (user == null)
{
ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditUserViewModel
{
Id = user.Id,
UserName = user.UserName,
};
ViewBag.UN = user.UserName;
return PartialView("~/Views/Modals/_DeleteModalPartial.cshtml", model);
}
if (type == "roleUser")
{
ViewBag.Type = "roleUser";
var role = await roleManager.FindByIdAsync(id);
if (role == null)
{
ViewBag.ErrorMessage = $"Role with Id = {id} cannot be found";
return View("NotFound");
}
var model = new EditRoleViewModel
{
Id = role.Id,
RoleName = role.Name,
};
ViewBag.Role = role.Name;
return PartialView("~/Views/Modals/_DeleteModalPartial.cshtml", model);
}
else
{
ViewBag.ErrorMessage = $"cannot be found";
return View("NotFound");
}
}
I am not sure why the click event on the button is not working at all. I have tried removing random code and literally nothing is making it go over to the controller at the least.
EDIT added javascript
$(function () {
var placeholderElement = $('#modal-placeholder');
$('[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
});
$('.sqButton').click( function (event) {
event.stopPropagation();
});
Since the button doesn't exist on page load you will have to create a event delegate to something that does exist on page load that will attach the event to the right element when it finally does appear in the DOM
In this case we will use the document (because it always exists on page load, some people use 'body') to delegate the event to the [data-toggle="ajax-modal"], like this:
$(document).on('click', '[data-toggle="ajax-modal"]', function (event) {
// code here
});
This will attach the event to the [data-toggle="ajax-modal"] elements on page load AND after page load if the element gets added later.
Try replacing your javascript code
$('.sqButton').click( function (event) {
event.stopPropagation();
});
With the following code
$('.sqButton').click(function(event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
if you manually force click, does it hit your controller?
document.querySelector('.btnRed').click();
is there any other element(s) "hijacking" click event?

Dynamic content data id not working in jquery

Have a dynamic html div
<a data-id="17" onclick="getcustomer();">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
On the above anchor's on click.it calls this function
function getcustomer(){
var id = $(this).data('id');
alert (id);
$.post(base_url+'who/customer', {
customer_id: id
}, function(data, status){
console.log(data);
});
}
But alert receiving is undefined.
How will I take data-id value?
This is dynamic field. This a's are added after dom load.
this does not refer to the element but to window
Pass this as argument for getcustomer function
function getcustomer(elem) {
var id = $(elem).data('id');
alert(id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" onclick="getcustomer(this);">
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
Or better use jQuery event binding using .on method
$('.eventBinding').on('click', function() {
var id = $(this).data('id');
alert(id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a data-id="17" class='eventBinding'>
<div class="note note-success">
<h4 class="block">A</h4>
<p>Email : a#gmail.com</p>
<p>Mobile : 8</p>
<p>DOB : 0000-00-00</p>
</div>
</a>
Pass the object to the method,
<a data-id="17" onclick="getcustomer(this);">
Then the code will be,
function getcustomer(obj) {
var id = $(obj).data('id');
alert(id);
$.post(base_url + 'who/customer', {
customer_id: id
},
function(data, status) {
console.log(data);
});
}
Try this:
<a data-id="17" onclick="getcustomer(this);">
function getcustomer(curr_obj){
var id = $(curr_obj).data('id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}
What if you use $(this).attr('data-id');
Try this as well, if it works. Its just simple one line of code.
$('a').on('click', function(){
var id = $(this).attr("data-id");
alert(id);
});
Or you can try this as well, according to your code,
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}
Use this script
function getcustomer(){
var id = $(this).attr('data-id');
alert (id);
$.post(base_url+'who/customer',
{
customer_id: id
},
function(data, status){
console.log(data);
});
}

Use dynamic div IDs with jQuery

I have a container which is filled with max. 20 items, each item gets its information (such as image) from an SQL database and an own div with id suit_(1-20).
The items get listed in the code below:
<?php
$d = 1;
?>
<table >
<tbody>
<?php while $item = sqlsrv_fetch_object($user_item) : ?>
<td align="center" height="50" width="21%">
<div class="tooltips" href="">
<div class="suitable" id="suit_<?php echo $d++ ?>" name="<?php echo $myDBID ?>">
<img src="images/icon/<?php echo $item->Img ?>">
</div>
</div>
</td>
<?php endwhile; ?>
</tbody>
</table>
As you see each div has the id suit_(d++) which means 1-20 for max 20 items.
Those divs have a jQuery script to trigger a contextual menu event on right click:
$(function () {
var count;
for(count = 1; count < 21; count++) {
var ID = document.getElementById('suit_' + count).getAttribute('id');
$('#suit_' + count).contextPopup({
items : [{
label : 'Set',
action : function () {
window.location.href = "?settest=" + ID
}
},
null,
{
label : 'Throw',
action : function () {
window.location.href = "?throwtest=" + ID
}
},
]
});
}
});
I have a for-loop which should count from 1 to 20 and generate the appropriate ids (suit_1 to suit_20).
Somehow the script works only for the last item in the container, so if I have 10 items in it, all items will get the ID suit_10.
Any ideas?
Why not remove the loop, and use an starts with attribute selector?
Using the ^= selector says "anything that starts with":
// A bit "safer" document ready, won't collide with other libraries that use $
jQuery(function($) {
// Select all items with ID starting with "suit_"
$('[id^="suit_"]').contextPopup({
items : [{
label : 'Set',
action : function () {
window.location.href = "?settest=" + $(this).attr('id');
}
},
null,
{
label : 'Throw',
action : function () {
window.location.href = "?throwtest=" + $(this).attr('id');
}
},
]
});
});
I solved the issue by adding an each(function()) for the selector and setting a variable object before the event starts.
The problem with the previous solution was the child function
action : function () {
window.location.href = "?settest=" + ID
}
which caused that $(this)was not working.
See the full code below:
jQuery(function($) {
$('[id^="suit_"]').each(function(){
var object = this;
$(object).contextPopup({
items : [{
label : 'Set',
action : function () {
window.location.href = "?settest=" + object.id
}
},
null,
{
label : 'Throw',
action : function () {
window.location.href = "?throwtest=" + object.id
}
},
]
});
});
});

isNan using this selector with dynamic content in jQuery

Here's the function I'm trying to use
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var data = {"action": "voteKarma", "id": $(this).data("id"), "value": $(this).data("val")}
$.post(window.apiURL, data, function(result) {
switch(result['status']) {
case 1:
var vote_sum_text = $(this).next(".sum").text();
if (!isNaN(parseInt(vote_sum_text, 10))) {
var vote_sum_text = $(this).next(".sum").text();
} else { alert("isNaN Variable") }
break;
}, 'json');
});
When the Ajax result returns 0 It's returning an alert with isNaN Variable which is my fallback to debug with problem.
Here's my HTML layout which is grabbed dynamically using another Ajax request there are multiple of these divs listed in <li> format :
<div class="votes pull-left">
<a class="up-vote" href="#" data-id="20" data-val="1"><span class="fa fa-arrow-circle-o-up"></span></a>
<span class="sum" style="font-weight:400;color:#666;">
0
</span>
<a class="down-vote" href="#" data-id="20" data-val="0"><span class="fa fa-arrow-circle-o-down"></span></a>
</div>
In simple terms; when you click .up-vote or .down-vote it'll send an AJAX request that'll then grab the text() of the .sum value.
Try use
$(event.currentTarget).next(".sum").text();
Because this in .post does not refer to element
You can also use the following:
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var up_vote_this = $(this);
....
....
//now you can use the variable in the success function...
var vote_sum_text = up_vote_this.next(".sum").text();

Go a few levels up the DOM hierarchy to the containing table row

I have an HTML structure like so:
<tr class = "#rowOrdinal" id = "...">
<td>
<a href = "#">
<img src = "/Content/updateIcon.gif" class = "updateResourceImageButton" id = "..." />
</a>
<a href = "#">
<img src = "/Content/cancelIcon.gif" class = "cancelImageButton" />
</a>
</td>
<td class = "hiddenColumn" id = ...>...</td>
<td class = "resourceKeyColumn" id = ...>...</td>
... and so on...
When the update link is clicked, I'd like to get the reference to the row, i.e. tr element in which the update hyperlink was.
So, in the below event listener, I'd like to go up the DOM hierarchy a few levels. I could use simple JavaScript and use a while loop to get the parentNode, but how would I do that with jQuery?
function WireHandlers() {
$('.updateResourceImageButton').click(UpdateResourceLinkClickedHandler);
}
function UpdateResourceLinkClickedHandler() {
// how do I get a reference to the tr that contains
// the hyperlink which is the source of this event?
}
$(document).ready(function () { WireHandlers(); });
You are looking for .closest() method:
function UpdateResourceLinkClickedHandler() {
var $tr = $(this).closest('tr');
}
function WireHandlers() {
$('.updateResourceImageButton').click( function(){
var trParent = $( this ).parent().parent();
UpdateResourceLinkClickedHandler();
});
}
Not sure why you need parent tr reference, so haven't used it in my example

Categories