get the id of parent tr for a child td - javascript

I want to get the id of the parrent tr of the td:
In this Jsfiddle I'm getting the id the td which has been chacked; I just return this value only if one row has been checked!
but
$(this).parent().attr("id")
gives me an undefined error! What is the correct way to get the id of parrent?
Thanks

When you use $(this).parent().attr("id") what you actualy get is TBODY element, try using closest('table') or parents('table') instead to find the parent TABLE of your TR.
From your example:
$("#my_tbl").find("tr").each(function() {
if ($(this).find("td:first").hasClass('checked'))
{
count = count + 1;
id = ($(this).closest('table').attr('id'));
// id = ($(this).parents('table').attr('id'));
}
});
Fiddle Demo

You can use:
id = $(this).attr("id");
It's because you're looping through the tr of your table using $("#my_tbl").find("tr").each( so you're already at the tr level.
So there's no need to use parent() to traverse up to the parent anymore, you just need to use $(this) to target current row tr of checked td instead.
Fiddle Demo

try with
just this works check demo
$(this).attr("id");
$(this) here is referring to tr only
Fiddle Demo

You just need to set this:
id = $(this).attr("id");
This is because you are working with currently with that tr.

First, you need to check if parent tag/node has id attribute or not. Also, you would get a better answer if you could share what's your objective and relevant HTML

use toggleClass() to switch the class
use .map() to get the ids of checked tr elemets
Try
function myFunction(element) {
$(element).find("td:first").toggleClass('checked');
}
function check() {
var ids = $("#my_tbl tr td.checked").parent().map(function () {
return this.id;
}).get();
if (ids.length > 0) {
alert(ids.join());
}
}
Demo: Fiddle
A more jQueryish solution will be is to use jQuery event handlers like
jQuery(function ($) {
$('#my_tbl tr').click(function () {
$(this).find("td:first").toggleClass('checked');
})
$('#check').click(function () {
var ids = $("#my_tbl tr td.checked").parent().map(function () {
return this.id;
}).get();
if (ids.length > 0) {
alert(ids.join());
}
})
})
Demo: Fiddle
If you want to support IE7+ only then try this

Related

Set the second option value according to the first option using jquery

I have a table. And I dynamically add rows to the table using jquery.
Each row has 3 select tag. I want to set the value of third option as same as the second one selected.
Here is my code:
$('#table tr').each(function () {
$(this).find('select:eq(1)').change(function () {
var selectedVal = $("#table").find('select:eq(1)').val();
$('#table').find('select:eq(2)').val(selectedVal);
});
});
But my problem is it just worked for only one row. What wrong with my code?
JSFiddle
Delegate event and use as selector tr td:nth-child(2) select:
$('#table').on('change', 'tr td:nth-child(2) select', function () {
$(this).closest('tr').find('select:eq(2)').val(this.value);
});
-jsFiddle-
Use Event Delegation for dynamic events.
$('#table').on('change', 'tr select:nth-child(1)',function() {
//traverse to the parent row
var tr = $(this).closest('tr');
//Find the second select
var secondSelect = tr.find('select:eq(2)');
//Set value
secondSelect.val($(this).val());
});
DEMO
First off:
var selectedVal = $("#table").find('select:eq(1)').val();
should probably be:
var selectedVal = $(this).find('select:eq(1)').val();
else you are only getting the first row's select...
But a little nicer might be:
$('#table tr').each(function(iter, elem) {
$(elem).find('select:eq(1)').change(function(){
var selectedVal=$(this).val();
$('#table').find('select:eq(2)').val(selectedVal);
});
});

Access jquery object when binding it using delegates

In my previous post I want it to find specific dom elements. The jquery selector using find provided in the solution was great. But I want to delegate this selector to bind it with "contextmenu" event. But it won't work if you pass jquery object in the delegate. What I do is the following.
var slots;
slots = $(".fc-slats > table tbody tr ").find("td:eq(1)");
$(".fc-agenda-view").on("contextmenu", slots, function (e){
e.preventDefault();
if (paste===true) {
showSlotContextualMenu($(this), e);
}else{
console.log($(this));
}
});
I want $this object to be the slot but I read that I cannot use jquery object in "on" but I need to use a selector. What would be the equivalent selector for this?I want the td that is second child from the desired tr. Is it
.fc-slats > table tbody tr td:eq(1)
The second parameter of on should be a string selector to find the descendant elements of the primary selector. With that in mind, this should work:
$(".fc-agenda-view").on("contextmenu", '.fc-slats > table tbody tr td:eq(1)', function(e) {
// your code...
});
Does this work?
$(document).on("contextmenu", ".fc-slats > table tbody tr > td:first-child", function (e){
// .....
});
What worked was the following.
var selector = ".fc-slats > table tbody tr td:nth-child(2)";
$(".fc-agenda-view").on("contextmenu",selector , function (e){
e.preventDefault();
if (paste===true) {
showSlotContextualMenu($(this), e);
}else{
console.log($(this));
}
});

Removing rows from table

Assume we have table:
<table>
<tr>first</tr>
<tr class="ClassName">second</tr>
<tr class="ClassName">third</tr>
</table
And We want to remove row with class='ClassName'
I wrote a code:
var Ids = $('.ClassName').map(function () {
return this
}).get();
if (Ids.length > 0) {
for (var i; i = 0; i++) {
Ids[i].hide();
}
}
I need to know if there are any rows with this class. If yes I need to remove them. If no I call ajax, read from db and add rows to table. Its part of Show/Hide mechanism
But my code do nothing. Rows still appear in the page. What should I change?
jQuery
// check if are any rows with this class
var $rows = $('table tr.ClassName');
if( $rows.length > 0 ) {
// remove them or hide with .hide();
$rows.remove();
} else {
// call ajax ...
}
Why not just:
$('table tr.ClassName').hide();
if you want remove permanent then you can use this one.
$('.ClassName').each(function(){
$(this).remove();
});
Here you go -
$("table tr[class='ClassName']").remove();
Please mark this as "Answered" if this solves your problem.
Try using hasClass() in jquery.
JQuery:
//Check if any row has class
if($('table tr').hasClass("ClassName")){ //remove from table }
else{
//do your ajax call here.
}
You can just remove all with that class and then check if there was any:
$(function () {
var $trs = $('table tr.ClassName');
$trs.remove();
if ($trs.length === 0) {
// Ajax-call
}
});
It should work
$("table").find(".ClassName").remove();
If you want to remove all the table rows other than first row means you can try this
$("table").find("tr:gt(0)").remove();

How to restore Textbox Data

I have a small requirement,
We have restore the textbox data that was cleared previously.
Below is my HTMl code
<table>
<tr><td><input type="textbox"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
Here is my JQuery Code
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val("")
}
if(!$(this).prop('checked'))
{
$(this).parents('TR').siblings('TR').find('input').val(?)
}
});
My Requirement is to clear the textbox content if checkbox is checked. And if i deselect it the textbox should be restored with previous data.
Please someone help me.
Use a global variable to store the previous data -
var prevData;
then modify your code this way -
$('TABLE TR TD').find(':checkbox').change(function()
{
if($(this).prop('checked'))
{
var $element = $(this).parents('TR').siblings('TR').find('input')
prevData = $element.val();
$element.val("");
}
else
{
$(this).parents('TR').siblings('TR').find('input').val(prevData);
}
});
When the checkbox is being checked, before clearing the value, store it using the jQuery .data() API.
<table>
<tr><td><input type="text"></td></tr>
<tr><td><input type="checkbox"></td></tr>
</table>
$('input:checkbox').change(function() {
var input = $(this).closest('table').find('input[type="text"]');
if ($(this).prop('checked')) {
input.data('text', input.val());
input.val('');
} else {
input.val(input.data('text'));
}
});
A demo which works if there were multiple pairs, so long as they exist in separate <table> parents. You could change the finder to get the previous sibling if that were not the case. This uses no global variables which are not really best practice - How to avoid global variables in JavaScript?.
Edit: Updated demo based on your other question Keydown event is not working properly but this will only for key events and not if someone pastes text into the <input>.
I'd suggest something a little less reliant on the mark-up remaining the same (though it does require that the checkbox follows the text input):
var prevData, textInputIndex;
$('input:checkbox').change(
function(){
thisIndex = ($(this).index('table input') - 1);
textInput = $('table input').eq(thisIndex);
if ($(this).is(':checked')) {
prevData = $(textInput).eq(thisIndex).val();
$(textInput).eq(thisIndex).val('');
}
else {
$(textInput).eq(thisIndex).val(prevData);
}
});
JS Fiddle demo.
Edited to remove the problem of having only one variable to store the text-input value:
var $textInputs = $('table input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('table input') - 1;
textInputIndex = $('table input').eq(affectedTextInputIndex).index('table input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
Edited to remove the explicit requirement that the input elements be contained in a table:
var $textInputs = $('input:text');
var prevData, textInputIndex, affectedTextInputIndex, textInputValues = [];
$('input:checkbox').change(
function(){
affectedTextInputIndex = $(this).index('input') - 1;
textInputIndex = $('ul input').eq(affectedTextInputIndex).index('input:text');
if ($(this).is(':checked')) {
textInputValues[textInputIndex] = $textInputs.eq(textInputIndex).val();
$textInputs.eq(textInputIndex).val('');
}
else {
$textInputs.eq(textInputIndex).val(textInputValues[textInputIndex]);
}
});
JS Fiddle demo.
References:
:checkbox selector.
change().
is().
:checked selector.
index().
val().

jQuery: Selecting an element in inside an already selected element

For example:
$("table tr").click( function(event)
{
//Say, here i want get the data of td element where its class name="special"
});
Is there any way I can select a element while in the click event, a element under the attached element above $("table tr")?
In this specific case, you can do this:
$("table tr").click( function(event)
{
$(this).children('td.special').whatEverYouNeed();
});
Generally speaking, you need to use find():
$("table tr").click( function(event)
{
$(this).find('td.special').whatEverYouNeed();
});
Something like
$(this).find(".special").html();
I think that that works

Categories