jquery how to get the class of parent element using chlid id? - javascript

I'm trying to alert the table(parent) class on click using the child id <th id="first">.
alert($(this).parent('tr').attr('class')); using this i have got the class of the <tr>.
But i want to get the class of the table when i use alert($(this).parent('table').attr('class')); it showing alert says undefined can someone help me how can the parent class using the child id
<table class="table table-bordered">
<thead>
<tr class="sample">
<th id="first">Firstname</th>
<th id="last">Lastname</th>
<th id="user">Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>arun </td>
<td>kumaresh</td>
<td>arun kumaresh</td>
</tr>
</tbody>
</table>
</div>
<script>
$(document).ready(function(){
$("#first").click(function(){
alert($(this).parent('tr').attr('class'));
});
});
</script>

Use .closest(TARGET_SELECTOR), For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
As .parent(SELECTOR), Get the parent of each element in the current set of matched elements, optionally filtered by a selector. (the parent() method traverses to the immediate parent)
$(document).ready(function() {
$("#first").click(function() {
alert($(this).closest('table').attr('class'));
});
$("#last").click(function() {
alert($(this).closest('thead').attr('class'));
});
$(".user").click(function() {
alert($(this).closest('table').attr('class'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table class="table table-bordered">
<thead class='ANY_CLASS'>
<tr class="sample">
<th id="first">Firstname</th>
<th id="last">Lastname</th>
<th class="user">Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>arun</td>
<td>kumaresh</td>
<td>arun kumaresh</td>
</tr>
</tbody>
</table>

simply use
alert($(this).closest('table').attr('class'));
refer closest here
https://api.jquery.com/closest/

Related

Retrieving column values from a table by clicking row with jquery and html

I'm using html5 and jquery to set up a dynamic table, until then I can add the elements to the table without problems, but I can not retrieve the value of its columns. so I have the following questions:
How can I recover the table data by clicking the ROW?
Should I always use the data-name, id for example as in the first
line ?
$(document).on("change", "#TabClientesAdicionados", function(e) {
alert('?');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
How can I recover the table data by clicking the ROW?
You can bind the click event to your TR elements and get the information.
Should I always use the data-name, id for example as in the first line?
Yes, because you don't want the parsed HTML to manipulate data. The data attributes are a better approach to keep related data (no HTML) to DOM elements.
Look at this code snippet
This approach binds the click event to TR elements
$('#TabClientesAdicionados tbody tr').click(function() {
var data = { name: '', id: '' };
$(this).children('td').each(function() {
var name = $(this).data('nome');
if (name) {
data.name = name;
}
var id = $(this).data('id');
if (id) {
data.id = id;
}
});
console.log(data);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno_1">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
I would do as the following snippet.
You need to bind the event to the row tr ant then get each of its children.
By adding a data attribute you could set a column name. This could also help if you eventually needed to extract the value of an specific cell.
Incidentally you could also add a second data attribute named like data-value or something similar- This in case you are worried that your parsed html content might cause you trouble with the values.
$(document).ready(function() {
$("#mytable").on('click', 'tr', onCellClick);
//Bind the event to the table row
function onCellClick() {
let row = $(this); //get the jquery Object for the row
let rowValues = {}; //An empty object to hold your data
let temp;
//extract the value of every cell in the row
//Doing it this way gives you flexibility on the amount of colums you have
row.find('td').each(function(item) {
temp = $(this);
rowValues[temp.data('column')] = temp.text();
//this could be changed to
//rowValues[temp.data('column')] = temp.data('value);
//if you desire to use a separate data-value property
});
console.log(rowValues);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%" id="mytable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td data-column="name" data-value="Jill">Jill</td> <!-Adding value property-->
<td data-column="lastname">Smith</td>
<td data-column="age">50</td>
</tr>
<tr>
<td data-column="name">Eve</td>
<td data-column="lastname">Jackson</td>
<td data-column="age">94</td>
</tr>
</table>

How to create table with multiline cells in React-bootstrap?

I want to create table where some cells contain several lines.
It's work if I do it:
<Table bordered>
<thead>
<tr>
<th>Date</th>
<th>Analysed ID</th>
<th>Analysed Name</th>
<th>Solve To change</th>
</tr>
</thead>
<tbody>
<tr>
<td rowSpan="3">Date</td>
</tr>
<tr>
<td>ID</td>
<td>Name</td>
<td>Decision</td>
</tr>
<tr>
<td>ID</td>
<td>Name</td>
<td>Decision</td>
</tr>
</tbody>
</Table>
I got it:
Table with multiline cell
And now I want to add my 3 "TR" tags in one component, because after I want use for-cycle to create many such components. But components must return content in one closed tag. I tried to contain my 3 "tr" in one parent "tr", but I got error. What can I do here?
It is not possible to create a React Component that returns three elements without wrapping them in another element, such as a div. Otherwise, you'll get the following error:
A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.
Your case here is a bit special, because you cannot have div's as the immediate child of table or tbody, so that's a problem...
What you can do however, is to create a class function that returns an array. Like this:
class MyApp extends React.Component {
getTr = () => {
return [
<tr key={0}>
<td rowSpan="3">Date</td>
</tr>,
<tr key={1}>
<td>ID</td>
<td>Name</td>
<td>Decision</td>
</tr>,
<tr key={2}>
<td>ID</td>
<td>Name</td>
<td>Decision</td>
</tr>
];
}
render() {
return (
<table className="table">
<thead>
<tr>
<th>Date</th>
<th>Analysed ID</th>
<th>Analysed Name</th>
<th>Solve To change</th>
</tr>
</thead>
<tbody>
{this.getTr()}
{this.getTr()}
{this.getTr()}
</tbody>
</table>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
You need to include tr tags in one div tag.
The right way to rowSpan is this:
var MyRow = React.createClass({
render: function () {
return (
<div>
<tr>
<td rowSpan="2">{this.props.item.date}</td>
<td>{this.props.item.data[0].id}</td>
<td>{this.props.item.data[0].name}</td>
<td>{this.props.item.data[0].solve}</td>
</tr>
<tr>
<td>{this.props.item.data[1].id}</td>
<td>{this.props.item.data[1].name}</td>
<td>{this.props.item.data[1].solve}</td>
</tr>
</div>
);
}
});
This is my working example: http://jsfiddle.net/andrea689/e33pd14L/

Find a element with particular name attribute or id in HTML with JQuery

I have a table with couple of columns, one of which is a link, on clicking it, I am calling JQuery click event. On click I want to get the value of a another column, which is a sibling of this column(td). how can i get it.
HTML
<table class="table table-bordered table-hover">
<thead>
<th>RID</th>
<th>Mobile Number</th>
<th>Outlet Name</th>
<th>Place</th>
<th>Email</th>
<th>Balance</th>
<th>Stock</th>
<th>Password</th>
</thead>
<tr>
<td data-name="rid">5111879</td>
<td data-name="mobile">9066587654</td>
<td data-name="outlet">Rachels</td>
<td>Indhiranagar, BL</td>
<td>rach#yahoo.com</td>
<td><i class="fa fa-inr"></i>378665</td>
<td>TRANSFER</td>
<td>RESET</td>
</tr>
</table>
on clicking the id=retailer_stock, a modal pops up and should have the value of data-name='rid'. How should i do it.
Javascript
$('#retailer_stock').click( function(event){
console.log($(this));
console.log($(event.target).closest('tr').children("[id = 'rid']"));
console.log($(this).closest('tr').children("[id = 'rid']"));
console.log($(event.target).closest('tr').find("[id = 'rid']"));
console.log($(event.target).siblings("[id = 'rid']"));
console.log($(this).closest("[id = 'rid']"));
})
of these code lines, last two is not working, its not fetching me a result, can any of you explain why?
-thanks
Use:
$('#retailer_stock').click( function(e){
alert( $(this).closest('tr').children().eq(0).text() )
})
Check demo: fiddle
If you want to access that cell through data-name attribute use:
$('#retailer_stock').click( function(e){
alert( $(this).closest('tr').find('[data-name="rid"]').text() )
})
However if you plan to have many rows in the table, you will end up with many elements with same retailer_stock id. To avoid this you may decide to change id="retailer_stock" to class="retailer_stock" and then change selector to $('.retailer_stock').
Using the Click event from jQuery:
https://api.jquery.com/click/
Capture the click on "retailer_stock" then you can retrieve the HTML from "rid"
http://api.jquery.com/html/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function () {
$('#retailer_stock').click(function (e) {
alert($(this).closest('tr').find('td[data-name="rid"]').text())
})
});
</script>
</head>
<body>
<table class="table table-bordered table-hover">
<thead>
<th>RID</th>
<th>Mobile Number</th>
<th>Outlet Name</th>
<th>Place</th>
<th>Email</th>
<th>Balance</th>
<th>Stock</th>
<th>Password</th>
</thead>
<tr>
<td data-name="rid">5111879</td>
<td data-name="mobile">9066587654</td>
<td data-name="outlet">Rachels</td>
<td>Indhiranagar, BL</td>
<td>rach#yahoo.com</td>
<td><i class="fa fa-inr"></i>378665</td>
<td>TRANSFER</td>
<td>RESET</td>
</tr>
</table>
</body>
</html>
$('#retailer_stock').click(function(e){
$(this).parent().find('[data-name="rid"]').text()
});

Getting unknown child div from parent?

<script type="text/javascript">
$(".inventory-notes").bind("click", function() {
if($(this).text().length > 0) {
alert($(this).text());
alert($(this).closest(".inventory-notes").children().text());
}
});
</script>
example table
<table id="inventory" class="table">
<thead>
<tr>
<th>Item</th>
<th>Value</th>
<th>Usage</th>
<th>Notes</th>
</tr>
</thead>
<tbody>
<tr class="items">
<td>Hatchet</td>
<td>24,000 Gold</td>
<td>Woodcutting</td>
<td><div class="inventory-notes"><div id="299"><img src="addnotes.png"></div></div></td>
</tr>
</tbody>
</table>
How can I get the value 299 from the child div of inventory-notes? The table really contains at least 1,000 rows of items each containing a random ID.
I am using jQuery 1.6.2 so I cannot use the .on() function.
Since you're using jQuery 1.6.2, I'd use .delegate:
$("#inventory").delegate(".inventory-notes", "click", function(){
var id = $(this).find("div").prop("id");
});
Since you're going to have 1,000+ rows, you don't want to bind the event to the actual rows, resulting in 1,000+ handlers.

Copy cell value from table to textbox

I have the following table. I want to copy Id value on the seleced row to the text box. If I click on link "Select" in the first row the text box value will 0001.
If the table needs modification to get result better and faster, please leave your suggestion.
<div>
<input id="selectedId" type="text" />
</div>
<table cellspacing="1" class="tablesorter" id="nameList">
<thead>
<tr>
<th class="header">Name</th>
<th class="header">Id</th>
<th class="header">Gender</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Akom Smith</td>
<td>0001</td>
<td>M</td>
<td>Select</td>
</tr>
<tr>
<td>Amara Sahara</td>
<td>0002</td>
<td>F</td>
<td>Select</td>
</tr>
<tr>
<td>John Lache</td>
<td>0003</td>
<td>M</td>
<td>Select</td>
</tr>
</tbody>
</table>
try this,
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td').eq(1).text();
$('#selectedId').val(id);
return false;
});​
simple cool demo
added notes for the comment below.
$('a.click-to-select').click(function() {
var id = $(this).closest('tr').find('td.id').text();
$('#selectedId').val(id);
return false;
});​
updated demo
Well, you know your key is the second td in the row. You can use the :nth-child selector like this:
<script type="text/javascript">
var getUniqueId = function() {
return $('td:nth-child(2)').text();
}
</script>
Of course you need a way to identify the correct , but I assume the code is supposed to be called from each and there you can use the parent selector.
Otherwise I'd put an id attribute in each row to make selecting easier.

Categories