I have a table full of appointments. Every appointment has two buttons. One for canceling the event, one for accepting it.
I am struggling to get the appointmentId in the jQuery function when I click on a button. Can you please give me a hint how to do this? The appointmentId is in the table as a hidden input field.
// my html code
<tr>
<td align="left">
<input type="hidden" name="appointmentId" value="234">
John Smith - 14.03.2013 at 9 o'clock
</td>
<td align="right">
<input type="button" id="acceptEvent" class="acceptEvent" value="Accept">
<input type="button" id="cancelEvent" class="cancelEvent" value="Cancel">
</td>
</tr>
// my jQuery code
$("body").delegate('.acceptEvent', 'click', function() {
console.log('accept event clicked');
// get the appointmentId here
});
$("body").delegate('.cancelEvent', 'click', function() {
console.log('cancel event clicked');
// get the appointmentId here
});
Use closest to grab the parent tr element, then select your hidden field.
The reason that this is the correct answer is because it takes the context of the click event with $(this). Then it travels up the DOM tree to your root table row element and selects the child by name. This ensures that you are always in the correct row.
EDIT: I know you already selected an answer, but this was really bothering me that it wasn't working properly. I had to walk down twice using .children() to get it to work though you could also use .find('input[name="appointmentId"]'). Even though you've already selected your answer, I hope this will help you.
$('.acceptEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
$('.cancelEvent').click(function() {
var myVal = $(this).closest('tr').children().children().val();
});
In the click function, you have access to the button that was clicked with this so you can do:
$("body").on('click', '.cancelEvent', function() {
var input = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
Assuming you have no other IDs or classes to key off of, you can use jQuery's Attribute Equals Selector in reference to the clicked button's parent tr element:
$('.acceptEvent').click(function() {
// get the appointmentId here
var appointmentId = $(this).closest('tr').find('input[name="appointmentId"]').val();
});
I'll do it like that :
$("body").on('.acceptEvent', 'click', function() {
var id = $('input[name="appointmentId"]').val();
//Or search in the parent <tr>
var id = $(this).parent().find('input[name="appointmentId"]').val();
console.log('accept event clicked');
console.log('Id is ' + id);
});
Related
I am populating a data-table from a model using a foreach loop:
#foreach(var item in Model)
{
<tr>
<td style="display: none">#item.Id</td>
<td>#item.Name</td>
<td>#item.Description</td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-default" data-dismiss="modal">Update</button>
<button type="button" data-id=#item.Id id="Delete" class="btn btn-danger" data-dismiss="modal">Delete</button>
</div>
</td>
</tr>
}
Each row of the table has an update and delete button.
I'm struggling to bind the buttons to a click event using jQuery.
Here is my script so far which is within the document ready function:
var table = $('#productTable').DataTable();
$('#productTable tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert(Product ID = ' + data[0] + ');
//Call delete function and pass in Id
});
This is understandably showing an alert anytime the user clicks the row. How to I get it to only fire when the delete button is clicked?
Thanks in advance for any help.
You can take doutriforce suggestion and bind the events to a class, for example:
$("#productTable tbody").on("click", ".btn-update", function() {
// Your update code here
// Use $(this) to access the button that triggered this event
}
$("#productTable tbody").on("click", ".btn-delete", function() {
// Your delete code here
// Use $(this) to access the button that triggered this event
}
I've used: $("#productTable tbody").on("click", ", function); because it also works for dynamically added elements (in this case, table rows).
Based on the documentation here, it looks like you need to edit the selector that you bind the click event too, like this:
$('#productTable button#Delete').on('click', function () {
var data = table.row(this).data();
alert(Product ID = ' + data[0] + ');
});
const medias = document.querySelectorAll('._23fpc');
for (let i=1; i<medias.length; i++) {
const media = medias[i];
const firstClickable = media.querySelectorAll('._1JX9L')[1];
if(firstClickable) {
window.setTimeout(() => firstClickable.click(), 50);
}
}
I edited the code copied from the internet, it kind of works
PS:I know nothing about coding
I need to have multiple buttons on page (created through a PHP loop) - there's not fixed number of buttons as there'll be one for each record displayed. I'd like to get the value of that button with javascript when it is clicked.
So far the html looks like:
<button id="update[0]" value="test">Update</button>
<button id="update[1]" value="test">Update</button>
<button id="update[2]" value="test">Update</button>
etc....
and my script is:
$(document).ready("#update").click(function() {
var updateId = $("#update").val
alert(updateId);
});
So far the script detects when any #update[] button is clicked but how do I know the index of the particular button in order to get the value (i.e. if #update[38] is clicked how do I know it's #update[38] so I can find the value of that particular button?
Thanks.
You do not want to chain off the document ready like you are as its returning the document.
$(document).ready("#update").click(function() {
So you are capturing the document.click not not button.click so when you reference $(this).val() you will get document.value which does not exist.
Should be:
$(document).ready(function () {
$("button").click(function () {
//no reason to create a jQuery object just use this.value
var updateId = this.value;
alert(updateId);
});
});
http://jsfiddle.net/SeanWessell/2Lf6c3fx/
Use the "this" key word.
$(document).ready("#update").click(function() {
var updateId = $(this).val();
alert(updateId);
});
The this keyword in javascript allows you to reference the particular instance of the object you are interacting with.
Also, add "()" to the end of val.
I believe you meant to use
var updateId = $("#update").val()
With jQuery you can use $(this).val()
You could also get the text of the button using .text()
With pure Javascript you could use .value if the button has a value attribute
See this: Javascript Get Element Value
I would suggest the following
<button id="0" class="updatebutton" value="test">Update</button>
<button id="1" class="updatebutton" value="test">Update</button>
<button id="2" class="updatebutton" value="test">Update</button>
Use a class to apply your click function.
$(document).ready(function () {
$("updatebutton").click(function () {
var updateId = this.id;
alert(updateId);
});
});
And use the id to specify the index of the button.
The trick is to give all your buttons the same class and then use $(this) to find out which button was clicked.
Once you know the button, then you can check for any of its attributes like id, value or name.
$(function() {
$(".xx").on("click", function(evt) {
var clicked_button = $(this);
alert(clicked_button.attr("value"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update_1" class="xx" value="test1">Button 1</button>
<button id="update_2" class="xx" value="test2">Button 2</button>
<button id="update_3" class="xx" value="test3">Button 3</button>
Hi there a few things wrong with your javascript there.
You are attaching onClick to the document! The function ready returns the document.
Wrong:
$(document).ready("#update").click(function() {
Right:
$(document).ready(function () { $(valid_selector).click...
You are attempting to refetch the button with $('#update'), which 1 doesn't fetch anything, and two if it did would return all of the buttons. So use $(this) in the scope of the click function instead to refer to the button clicked.
Here is your javascript corrected:
https://jsfiddle.net/ffkekpmh/
//When the document is ready call this function
$(document).ready(function () {
//Select all buttons whoes id starts with update
//https://api.jquery.com/category/selectors/attribute-selectors/
$('button[id^="update"]').click(function() {
//Store the id attribute from the clicked button
var updateId = $(this).attr("id");
//Store the value attribute from the clicked button
var value = $(this).attr("value");
alert("You clicked button:"+updateId+" with value: "+value);
});
});
I am using Bootstrap 3.0 ContextMenu. here is a link http://jsfiddle.net/KyleMit/X9tgY/
I need to know how i can get the id or data-Id of the clicked element. i try many of the tricks but i cant get the clicked element id? Like when i clicked on "Jacob" row i get the "Jacob" after clicked. I also need from this line
<td data-id="user-3">
<a data-id="user-3">Jacob<a/>
<td/>
"data-Id"?
i tried var $selectedFileId = $(this).closest('a').html(); or alert($(this).parent('a').html());
Use this code for get clicked element id
jQuery(document).on('click', function(e){
console.log(e.target.id);
})
I get the id by little additions in the contextMenu handler, Changes
// click handler for context menu
function ContextMenuClickHandler() {
$(settings.menuSelector)
.off('click')
.on('click', function (e) {
$(this).hide();
var $invokedOn = $(this).data("invokedOn");
var $selectedMenu = $(e.target);
// My Changes
var $selectedFileId = $(this).data("invokedOn").find('.yourClass').attr('id');
settings.menuSelected.call($(this), $invokedOn, $selectedMenu, $selectedFileId);
});
}
I have a input type file field and there is a label near this like "Add more",this is a hyper link. While clicking on this hyper link it should create another input type file field. Once it is created an another input type file field there should be link like "Remove", clicking on this link will remove the corresponding file field only.
Note that there is no limit of adding this file fields, but in worst case I will upto 10 file fields maximun. I meant to say there should be no condition to check whether it reached the maximum limit.
You can see my code here.http://jsfiddle.net/inDiscover/6hVkw/
HTML
<table>
<tr id="bkup_doc_rw">
<td align="right"><label class="letter_font" for="bkup_doc_proof">Document :</label></td>
<td> <input type="file" name="bkup_doc_proof" id="bkup_doc_proof" required/> <a class="letter_font" style="text-decoration:none;cursor:pointer;" href="#" id="addNew">Add more </a>
</td>
</tr>
</table>
JQUERY
var fle_cnt = 1;
$('#addNew').click(function() {
fle_cnt++;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#bkup_doc_rw').after('<tr><td> </td><td>
<input type="file" name="bkup_doc_proof" id="bkup_doc_proof_'+fle_cnt+'"> <a class="letter_font" style="text-decoration: none;cursor: pointer;" href="#" id="remNew">Remove</a></td></tr>');
return false;
});
$(document).on('click', '#remNew', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#remNew').parents('tr').remove();
return false;
});
Here issue is when I tried to clike on "Remove" label it is not removing the corresponding file field instead it is removing randomly. I know this issue is happening because I am not using unique ID (file_cnt) while deleting a filed.
Can any one help me to modify my code in a better way to achieve this.
Try this:
var fle_cnt = 1;
$('#addNew').click(function (event) {
fle_cnt++;
event.preventDefault();
$('#bkup_doc_rw').after('<tr><td> </td><td><input type="file" name="bkup_doc_proof" id="bkup_doc_proof_' + fle_cnt + '"><a class="letter_font remNew" style="text-decoration: none;cursor: pointer;" href="#">Remove</a></td></tr>');
});
$(document).on('click', '.remNew', function (event) {
event.preventDefault();
$(this).closest('tr').remove();
});
changes:
in the #addNew click pass the event in the callback.
change the id attribute to class instead.
instead of id selector change to the class selector .remNew.
instead of $('#remNew') place the context selector as $(this).
pass the event in the callback of .remNew's click event
You don't need to use return false; as you are already using event.preventDefault(); and it would work if you pass the event in the callback as mentioned above.
and instead of .parents() use .closest() to traverse up.
Demo # updated fiddle.
htry this:
$(document).on('click', 'a.letter_font', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$(this).parents('tr').remove();
return false;
});
inside the click event use $(this). this way you can manage the exact object which triggered the event.
#remNew That why !
IDs are mean to be unique.
$('#remNew').parents('tr').remove();
to
$(this).parents('tr').remove();
HTML pages must have the ID's unique. Make the remNew a class and you're fine:
JSFiddle
var fle_cnt = 1;
$('#addNew').click(function() {
fle_cnt++;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$('#bkup_doc_rw').after('<tr><td> </td><td> <input type="file" name="bkup_doc_proof" id="bkup_doc_proof_'+fle_cnt+'" /> <a class="letter_font remNew" style="text-decoration: none;cursor: pointer;" href="#" >Remove</a></td></tr>');
return false;
});
$(document).on('click', '.remNew', function() {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$(this).closest("tr").remove();
return false;
});
You were using id = "remNew", should never use multiple id's - they are used specially to create unique identification,
for DOM elements with similar property we always use classes - so i replaced id with class = "remNew"
on click on some elements we able to detect it using this instance , and the use jquery closest to delete specific tr tag
make remNew as class, you can try this way too
`http://jsfiddle.net/MRqN4/`
I wanted to get the id of clicked button since i have 4-5 buttons on my form.
<button type="submit" style="height: 30px" id="btnHelp" name="btnHelp" onclick="ShowHelp(2);return false;">Help</button>
<button type="button" style="height: 30px" id="btnClose" name="btnClose" onclick="Close();return false;">Close</button>
<button type="button" style="height: 30px" id="btnSave" name="btnSave" onclick="Save();return false;">Close</button>
...............................
Whichever may be the button click, I just want to get id of that button.
$(function () {
var id = $(this).attr('id');
alert(id);
})
Also with
$("input").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
but i am getting the alert as undefined.
How can i get id of button clicked?
Please help me.
Try
:button Selector
Selects all button elements and elements of type button.
$(":button").click(function (event) {
var urlid = this.id;
alert(urlid);
});
Fiddle Demo
Problem
$("input") --> selects elements with tag input eg. <input type="text"/> but not <button> tag .
I'd try to replace this with the event triggerer.
var urlid = $(event.target).attr("id");
Also, probably your onclick function is preventing your script to be executed, because it's handling the click event, not letting your function do it.
I ditched the onclick attributes of buttons you have, and hooked click events to button rather than input, and it worked. So check whether you are connecting to the right element.
See example here.
<script>
jQuery(":button").click(function (event) {
var urlid = $(this).attr('id')
alert(urlid);
})
</script>
Try this its work
very simply:
$("input").click(function (event) {
var urlid = this.id;
alert(urlid);
})
for button:
$("button").click(function (event) {
var urlid = this.id;
alert(urlid);
})
You might try use event passed as argument into any event handler instead of this for event.target is referring to element actually triggering your handler (being clicked) and event.delegateTarget being element handler has been attached to initially. In both cases you might have to use $() for using jQuery or simply stick with accessing .id in either case.
In your case this would be
$("input").click(function (event) {
var urlid = $(event.delegateTarget).attr('id');
alert(urlid);
});
to ensure handler is always accessing that it has been attached to, here.
Except for this quite simple scenario relying on this is sometimes trickier than using provided arguments.
EDIT : However, your case seems to be related to issues encountered by Tusha Gupta, for sure. Your buttons aren't "inputs" so that handlers are never attached, actually.
$(function () {
$("button").click(function () {
alert($(this).attr("id"));
});
});