Get the value from a particular column - javascript

I'm trying to alert message on click each column. I have a table in which three row and four column, now I want alert message with next column value on third column click of each table. I have tried this but all column get value not a particular column. my problem is this is invoke in every column click but I want alert message only when third column click of each row.
HTML
<table id='myTable'>
<tr><td>R1C1</td><td>R1C2</td><td>R1C3</td><td>R1C4</td></tr>
<tr><td>R2C1</td><td>R2C2</td><td>R2C3</td><td>R2C4</td></tr>
<tr><td>R3C1</td><td>R3C2</td><td>R3C3</td><td>R3C4</td></tr>
</table>
JS
$("#myTable tr").bind("click", function () {
alert($(this).children("td").eq(3).html());
});
Demo Here

please try this code
$(document).ready(function () {
$('#myTable tr').each(function (Mindex, Mval) {
$(Mval).find('td:eq(2)').click(function () {
alert($(Mval).find('td:eq(3)').html());
});
});

Try this
$('table#myTable tr td:nth-child(3)').on('click', function() {
alert($(this).next().html());
});
Check Here

$("#myTable tr td:nth-child(3)").click(function () {
alert($(this).next().html());
});

Try this:
$('#myTable').children('tr').children('td').eq(3).on('click', function() {
alert($(this).next().html());
});
The above function makes sure that you are calling the direct children elements but not any nested other same elements. Solves future regressions.

If your table is going to stay the same size there are answers that already work. If your table is going to grow I would recommend doing some event delegation. It will dramatically speed up the page if there are going to be a large number of event listeners.
$('#myTable').on('click', 'td:nth-child(3)', function(){
alert($(this).text());
});
See this jsfiddle, and this jquery documentation.

below code will find and set the desired column value
$('#myTable tr:gt(0)').each(function(){
// console.log($('td:eq(3)', $(this)).html());
alert($('td:eq(3)', $(this)).html());
$('#myTable').find('tr:gt(0)').find('td:eq(3)').html("hello");
});

Try this:
var thirdEle = $("#myTable tr td:nth-child(3)");
thirdEle.bind("click", function () {
alert($(this).html());
});

Related

Using jQuery, how to have click event handler respond for selected table columns?

jQuery v1.11
Given an HTML table with 6 columns, I want the cells in the table in columns two, three, five and six to respond to click events. So if a user clicks on a cell in column one or four, the click event handler should not be called.
This prevents the event handler from being called when the user clicks in the first column:
$('#my-table').on('click', 'tbody td:not(:first-child)', function (e) {
alert("I've been clicked on!");
});
And his prevents the event handler from being called when the user clicks in column 4:
$('#my-table').on('click', 'tbody td:not(:nth-child(4))', function (e) {
alert("I've been clicked on!");
});
My question is, how do I modify the above so that the event handler is not called when a click occurs in either column one or four.
JSFiddle
Edit: #micnil answered my specific question and I will find knowing the pattern he suggested useful. However, #Oleg took the time to point out a better approach. Rather than binding the event handler to each cell, he suggested that I should bind an event handler to the table. In my case this proves to be better.
Using performance.now(), discussed here, I get the following results setting up the binding for a jQuery DataTable containing 1,000 rows in Chrome:
Binding the click event to cells took 0.14627581768183972 milliseconds.
Binding the click event to the table took 0.04619236347855349 milliseconds.
You can just put a coma inside the selector:
$('#my-table').on('click', 'tbody td:not(:nth-child(4), :first-child)', function (e) {
alert("I've been clicked on!");
});
I think the best choice in your case is to use the JQuery function index() that will give you the index of clicked td and you can do the condition you want based to the returned index, take a look at Your updated fiddle.
JS :
$('#my-table').on('click', 'tbody td', function () {
if($(this).index() < 4){ //click in td between 1 and 4
alert('td between 1 and 4 clicked');
}else{ //click in another td
alert('td between 5 and 6 clicked');
}
});
Hope that help.
It's important to understand, that the code like $('#my-table').on('click', 'tbody td:not(:first-child)', function (e) {...}); creates first jQuery wrapper with all <td> element which corresponds 'tbody td:not(:first-child)' selector and then bind the event handler separately to every from DOM elements in jQuery object.
I would recommend you to choose another way. You can make one binding of click on the whole <table>. The event bubbling will forward the click on the cell to the parent <tr> and later to the <table>. It's important that e.target get your the clicked <td>.
So the code could be the following:
var columnIndexesIgnore = [0, 3];
$('#my-table').on('click', function (e) {
var $td = $(e.target).closest("td"); // e.target can be <span> instead of <td>
if ($td.length > 0 && $.inArray($td[0].cellIndex, columnIndexesIgnore) < 0) {
// cellIndex is 0-based index. We display in alert 1-based column index
alert("I've been clicked on column " + ($td[0].cellIndex + 1) + "!");
}
});
I used cellIndex property of DOM of <td>. It's 0-based index of column of the <td> element. So you need ignore clicks if $td[0].cellIndex is 0 or 3.
See your demo after the modification: http://jsfiddle.net/OlegKi/spckrjvf/5/
You can check the desired condition by doing this.
$('td').click(function () {
var col = $(this).parent().children().index($(this));
var row = $(this).parent().parent().children().index($(this).parent());
if (col == 3 || col == 0) {
alert("I have clicked on column " + col);
} else {
alert("I have clicked on another column");
}
});

Table onclick rows jQuery

I've a table whose content is getting generated via an AJAX success response.
HTML code
<table class="table table-hover" id="table_content"></table>
AJAX code
$.ajax({
dataType: "json",
type : "POST",
url: "/configuration/",
data : { 'selected_item' : selected_item_id },
success : function(result){
var table_heading = "<tr>"
var table_content = ""
for (var heads in result[1]){
table_heading +="<th style='background-color:#f1f1f1;'>" + result[1][heads] + "</th>"
}
for (var region in result[0]){
table_content += "<tr>"
for (var details in result[0][region]){
table_content += "<td>" + result[0][region][details] + "</td>"
}
}
table_content = table_heading + table_content
$("#table_content").html(table_content)
},
});
I want to apply an onclick function to it. Like this:-
Onclick function code
$(function(){
$('#table_content tr').click(function () {
$('.test').slideUp(0)
$(this).append(($('.test')).slideDown('slow'));
});
});
The issue that I'm facing is that I'm not able to click the row, if I generate the content via AJAX response. If I create a table inside the HTML itself, it'll work, but not when the table is created via AJAX response.
What's the problem? Please sugggest.
EDITED
What I'm trying to achieve is that a div should be slide down just below the row upon clicking the row. I does works for the first time when the data gets generated via AJAX. but it does not works when I'm generating data after the first time, though the event is triggered but $('.test').slideUp(0) $(this).append(($('.test')).slideDown('slow')); does not works after the first time. Nor any error is popped . See http://jsfiddle.net/fVz6D/5/
Updated:
See working demo: http://jsfiddle.net/c5FgG/1/
Your problem was that you attached the test div element to a table row, which dissapeared after repopulating the table. Instead, clone the test div on each click when you are changing the table content, and use the clone instead the original.
Old answer:
Add the onclick function code inside the ajax success function. It works out for me this way:
...
$("#table_content").html(table_content);
$('#table_content tr').click(function () {
alert("Clicked");
//your code
});
...
And don't forget to close the table rows with:
table_content += "</tr>";
The way you are using click to bind the event only binds the event to elements that are present in DOM at time the binding code is executed. You need event delegation for binding event with dynamically generated html elements using on().
$(function(){
$('#table_content').on('click', 'tr', function () {
$('.test').slideUp(0)
$(this).append(($('.test')).slideDown('slow'));
});
});
Delegated events
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time. By
picking an element that is guaranteed to be present at the time the
delegated event handler is attached, you can use delegated events to
avoid the need to frequently attach and remove event handlers, reference.
Try
$(function(){
$('#table_content').on('click', 'tr', function () {
$('.test').slideUp(0)
$(this).append(($('.test')).slideDown('slow'));
});
});
The on() handler should work on newly created elements too.
$(function(){
$('#table_content').on('click', 'tr', function () {
$('.test').slideUp(0)
$(this).append(($('.test')).slideDown('slow'));
});
});
Here Is a list of fiddles :
fiddle1
fiddle2
fiddle3
fiddle4
You can use it as per your requirement.
Use on() for dynamically added elements like,
$('#table_content').on('click',' tr', function () {
$('.test').slideUp(0)
$(this).append(($('.test')).slideDown('slow'));
});
Updated your div will move to tr which you clicked, so when you click on list it will generate new content in table so your div.test will be removed from HTML, thats why you are not getting the desc div again.
To solve this problem you have to add div.desc again in clicking of list like,
if(!$('body > div.test').length){
$("body").append('<div class="test">You slide down a row with content xyz</div>');
}
Full code
$('#list').on('click', 'li', function () {
var id = this.id;
var table_content = "";
// IF id=1,2,3,4,5 Code
$("#table_content").html(table_content);
// add below code foe div.desc
if (!$('body > div.test').length) {
$("body").append('<div class="test">You slide down a row with content xyz</div>');
}
});
Demo
Alternatively, you can use clone() like,
$(function () {
$('#table_content').on('click', 'tr', function () {
$clone=$('.test:not(.new-test)').clone();// clone the first test class element
$('.new-test').remove();// remove the cloned elements
$clone.addClass('new-test').appendTo('body');// add the clone to body
$clone.slideUp(0);// playing with clone now
$(this).append($clone.slideDown('slow'));
});
});
Working demo

Onclick not working on Knockout array binded fields

Im working on a CRUD Table populated using Knockout. jQuery Click event is not working on new pushed elements to the observable array
click event function
$('td').on('click', function () {
var spanElement = $(this).find('span');
$(this).find('span').hide();
$(this).find('input').show().select().on('blur', function () {
$(this).hide();
spanElement.show();
});
});
This code is working for all rows populated on-load, but not for those I add using add button.
Why is it so? How to fix it?
JSFiddle
It does not work because you are adding the event handler directly to the table cells. When you add new rows, you never add the click element.
To solve this problem, apply the click event to the table and let event delegation take over
$('table').on('click', 'td', function () {
var spanElement = $(this).find('span').hide();
$(this).find('input').show().select().on('blur', function () {
$(this).hide();
spanElement.show();
});
});
Try this
$(document).on('click', 'table td', function () {
//Your Functions
});

Append Text in Last Column Using Jquery

I want to append the text in last column of the table (grid like structure). Like below
When Click on Add button i want to append some text in last column adjacent to Add button. I am getting repated text on click of Add as in picture above.
This is what i have tried so far (one step away):
$(document).ready(function(){
$('.new').on('click', function(){
var recId= $(this).parents("#myTable td:last-child");
recId.append('<b>Sometext</b>');
recId.css("background-color", "lightgreen");
});
});
Can someone help me rectify this, Sample JSFiddle
Edit for Clarity in question
Sometext added in last column is dynamic and click event on Add button should fire multiple times.
Try .one()
Attach a handler to an event for the elements. The handler is executed
at most once per element per event type.
$('.new').one('click', function () {
fiddle Demo
Updated after OP's comment.
fiddle Demo
$(document).ready(function () {
$('.new').on('click', function () {
var recId = $(this).parents("#myTable td:last-child");
if (recId.text().indexOf("Sometext") === -1) { //if it contains Sometext it will not append it again but if it's a new value it will append it
recId.append('<b>Sometext</b>');
recId.css("background-color", "lightgreen");
}
});
});
Better code
fiddle Demo
$(document).ready(function () {
$('.new').on('click', function () {
var recId = $(this).parent();
recId.find('b').remove();
recId.append('<b>Sometext</b>');
recId.css("background-color", "lightgreen");
});
});
Try:
$(document).ready(function(){
$('.new').on('click', function(){
var recId= $(this).parents("#myTable td:last-child");
recId.find('b').remove(); //remove text
recId.append('<b>Sometext</b>');
recId.css("background-color", "lightgreen");
});
});
DEMO here.
i did this to your JS.
$(document).ready(function(){
$('.new').on('click', function(){
var recId= $(this).parents("#myTable td:last-child");
if (!recId.hasClass("changed")) {
recId.append('<b>Sometext</b>');
recId.css("background-color", "lightgreen");
recId.addClass("changed");
}
});
});
checking if the td has the class "changed", if not: add text, change bgcolor and the add the class "changed" so the event can fire but won't do anything to the same td twice.

JQuery highlighting a row in an ajax loaded table

A page contains two tables. First table is loaded together with the whole page and the second table is loaded afterwards with the help of ajax.
Both tables contain links in each their row.
After clicking a link the corresponding table row (where link is) should be highlighted.
With the first table there are no problem. The following works ok:
$(document).ready(function () {
$('#firstTable tr a').click(function (event) {
$('#firstTable tr').css("background-color", "white");
$(this).closest('tr').css("background-color", "silver");
});
});
But there are problems with the second table. I try to use .live() method but with no success, it doesn't react on clicks:
function onLoad() {
$('#secondTable tr a').live('click', function () {
highlChooseRow();
});
}
function highlChooseRow() {
$('#secondTable tr').css("background-color", "white");
$(this).closest('tr').css("background-color", "silver");
}
What am I doing wrong?
How about
$(document).ready(function () {
$('#firstTable tr a, #secondTable tr a').live('click', function (event) {
$(this).parent('table').find('tr').css("background-color", "white");
$(this).closest('tr').css("background-color", "silver");
});
});
should work without any problems. for cleanup you could also define some class '.higlightable-table' or something like that and use $('.hightlightable-table a').live ...

Categories

Resources