kdubs
kdubs

Reputation: 946

Return table column value on row click using jQuery

I have an html table and I want the user to be able to click on a row of the table and have an alert pop up with a certain column value. I've been able to get the alert to work with returning the first column value in the selected row, but can't figure out how to get any other column information.

My javascript code looks like this so far:

$("#pass_table tr").click(function(){
  $(this).addClass('selected').siblings().removeClass('selected');    
    });

$('.ok').on('click', function(e){
  if($("#pass_table tr.selected td:first").html()){
    var retval = confirm("Continue using: "+$("#pass_table tr.selected td:first").html()+"?");
    if(retval == true){
      alert("it worked!")
    } else {
      alert("you canceled!!")
    }
  } else {
    alert("You must select a row.")
  }
});

and my html code looks like this:

<div class="table-responsive">
  {{ pass_table | safe }}
</div>
<form class="form-horizontal">
  <div class="text-center">
    <input type="button" class="btn btn-primary ok" value="Generate File"/>
  </div>
</form>

where pass_table is generated from a generic pandas dataframe (df) using DataFrame.to_html() like this:

html_table = re.sub(' pass_table', '" id="pass_table', df.to_html(classes='pass_table'))

How would I go about displaying info from column 13 of the selected row in my table?

Upvotes: 0

Views: 2516

Answers (2)

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

Currently you are using the :first css selector which gives you only the first column. You'll want to use the :nth-child() selector instead.

$("#pass_table tr.selected td:nth-child(13)").html()

See here: https://api.jquery.com/nth-child-selector/

Upvotes: 2

L. Monty
L. Monty

Reputation: 882

You can access the clicked element by the jQuery events target-property or easier $(this)

Any information about the clicked element you can get as usually

$(document).on('click', '.pass_table td', function(event){
      //zero-based colNo and rowNo
       var $col = $(this); // or $(event.target)
       var $row = $col.parents('tr:first').addClass('selected').siblings().removeClass('selected');
       var content = $col.text();
       var colNo = $col.prevAll().size();
       var rowNo = $row.prevAll().size();
       alert('content: ' + content + '; rowNo: ' + rowNo + ';colNo' + colNo);
    });

Here is a fiddle with a showcase

Upvotes: 1

Related Questions