Get row position of button clicked within an html table via javascript

Hi, I'm trying to get the row position of a button when it's clicked.  The button in question is 'btnCode' (see code below).
The table has one row and 3 columns, but when the data is populated and bind, it will create 20 tables (with one row each) inside the repeater.

  <asp:Panel ID="pnl" runat="server" CssClass="mypanel" EnableViewState="true">
       <asp:Repeater ID="rpt" runat="server”>
                    <ItemTemplate>
                         <table class="tblclass" id="tbl_id">
                               <tr>
                                   <td>
                                      <asp:Button ID="btn1”/>
                                                   
                                   </td>
                                   <td>
                                       <asp:Button ID="btn2"/>                                        
                                        
                                   </td>
                                  <td>
                                      <a class='danger btn btn-success btn-circle btn-sm'  runat="server" id="btnCode" href='#' 
                                                    role="button" onclick="GetPos(this)">Click me</a>
                                   </td>

                           </tr>
                     </table>
              </ItemTemplate>
        </asp:Repeater>
                   ...       
           

Open in new window


I tried to add a function to the onclick event of the button to return the row position
        function GetPos(element) {
            alert("row: " + element.parentNode.parentNode.rowIndex + " - column" + element.parentNode.cellIndex);
        }

Open in new window


But this code always returns the same result  (row: 0 - column: 2) as there is only one row per table.

I was thinking to add a handler to each button (btnCode) when my page loads through javascript.
I can get to loop though all 20 tables but I can't figure it out how to find, and reference, the button inside the row and <td> to assign the onclick event.

var tbl = document.getElementById('contentplaceholder1_pnl').getElementsByTagName('table');
    for (var i = 0; i < tbl.length; i++) {  --> this will give me 20 items in length.
        
      --find btnCode       
      --  store the value 'i' in a custom btnCode attribute to retrieve after clicking it? 
         

Open in new window


Im not sure if this is the right approach. Any other suggestions would be welcome!
Thanks
Adrian CrossAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

NorieVBA ExpertCommented:
Adrian

Do you actually want to get the table within the repeater in which the button has been clicked?
0
Chris StanyonWebDevCommented:
Couple of things to note here. In your repeater code, you're setting the ID of the button to btnCode. An ID needs to be unique in HTML, so if your code repeats 20 times, you will end up with 20 buttons all with the same ID. To resolve this issue, move the btnCode to the class attribute.

Also, in your repeater you can get the item index of the section, so you can use this to add a data attribute to the button, which you can then easily retrieve using jQuery:

<a class='danger btn btn-success btn-circle btn-sm btnCode' runat="server" href='#' role="button" data-number="<%# Container.ItemIndex +1 %>">Click me</a>

Open in new window

And the jQuery:

$('.btnCode').click(function(e) {
    alert("Row: " + $(this).data('number'));
});

Open in new window

1
Julian HansenCommented:
Why are you doing a table per row?
Why not have all your rows in one table?

If you have to do it this way then we can do this. First lets look at the code that is generated by the above
<div id="pnl" class="mypanel">
  <table class="tblclass" id="tbl_id">
    <tr>
      <td>
        <asp:Button ID="btn1"/>
      </td>
      <td>
        <asp:Button ID="btn2"/>                                        
      </td>
      <td>
        <a href="#" id="rpt_btnCode_0" class="danger btn btn-success btn-circle btn-sm" role="button" onclick="GetPos(this)">Click me</a>
      </td>
    </tr>
  </table>
  <table class="tblclass" id="tbl_id">
    <tr>
      <td>
        <asp:Button ID="btn1"/>
      </td>
      <td>
        <asp:Button ID="btn2"/>                                        
      </td>
      <td>
        <a href="#" id="rpt_btnCode_1" class="danger btn btn-success btn-circle btn-sm" role="button" onclick="GetPos(this)">Click me</a>
      </td>
    </tr>
  </table>
</div>

Open in new window

As you can see the asp:panel has wrapped the tables in a <div> - this is good because it gives us a common parent for all the tables.

We can now bind to the button and do this
<script src="http://code.jquery.com/jquery.js"></script>
<!-- START "jQuery" -->
<script>
function GetPost(el) {
	var index = $(el).closest('table').index();
	console.log(index);
	return false;
}
</script>

Open in new window

Note the return false - if you use this method (onclick make sure to change your asp code to this
<asp:Repeater ID="rpt" runat="server" DataSourceID="SqlDataSource1">
  <ItemTemplate>
    <table class="tblclass" id="tbl_id">
      <tr>
        <td>
          <asp:Button ID="btn1"/>
        </td>
        <td>
          <asp:Button ID="btn2"/>                                        
        </td>
        <td>
          <a class='danger btn btn-success btn-circle btn-sm'  runat="server" id="btnCode" href='#' 
            role="button" onclick="return GetPost(this)">Click me</a>
        </td>
      </tr>
    </table>
  </ItemTemplate>
</asp:Repeater>

Open in new window

Note the return in the onclick. We need this to disable default behaviour on the <a> and putting a '#' in the URL

To do it the jQuery way remove the onlick and do this
<html>
<body>
<asp:Panel ID="pnl" runat="server" CssClass="mypanel" EnableViewState="true">
  <asp:Repeater ID="rpt" runat="server">
    <ItemTemplate>
      <table class="tblclass" id="tbl_id">
<!-- REMEMBER TO CHANGE YOUR ID's ON YOUR BUTTON's -->
        <tr>
          <td>
            <asp:Button ID="btn1"/>
          </td>
          <td>
            <asp:Button ID="btn2"/>                                        
          </td>
          <td>
            <a class='danger btn btn-success btn-circle btn-sm'  runat="server" id="btnCode" href='#' 
              role="button" >Click me</a>
          </td>
        </tr>
      </table>
    </ItemTemplate>
  </asp:Repeater>
</asp:panel>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- START "jQuery" -->
<script>
$(function() {
  // YOU MIGHT WANT TO ADD ANOTHER CLASS 
  // TO YOUR BUTTONS TO ISOLATE THE ONES YOU 
  // WAN THIS EVENT HANDLER TO FIRE ON
  // I HAVE USED THE id OF THE PANEL 
  $('#pnl .btn').click(function(e) {
    e.preventDefault();
    var index = $(this).closest('table').index();
    console.log(index);
  });
});
</script>
</body>
</html>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Slick812Commented:
greetings  Adrian Cross , , , ,  there are several many ways to do what you say you need, as the <a> button thing is not really in an indexed element, I agree with Julian Hansen that it may be best to have one table and 20 <tr> rows, BUT with the javascript I have next it will not matter if there are 20 <table>  or  20 <tr> I used a test where I made several tables each with an <a> danger class, and I assigned a property as -
    .rowNum01
as the Index from the first <a> and set an onclick event -

<script>

var dangers = document.getElementById('contentplaceholder1_pnl').querySelectorAll("a.danger");
for (var i=0; i < dangers.length; ++i) {
  dangers[i].rowNum01 = i;
  dangers[i].onclick = function() {
	alert("the ROW number is= "+this.rowNum01);
// next is just a test code to show you how to accesss the <td> that holds the <a>
	this.parentElement.style.backgroundColor = "#ddd";
    }
  }

</script>

Open in new window


you must run this code AFTER the <a> danger have been placed in the DOM, I am NOT sure what use the <a> index will be for you to use it to do any thing? But if you have an array with all the <table> or have row <tr> indexs , then it may be useful, if you just need to get an element in that row to do something you can use -
    this.parentElement
or
    this.parentElement.parentElement

to find stuff in that row
0
Adrian CrossAuthor Commented:
Thanks everyone for your input!
0
Slick812Commented:
this question has been inactive for more than 14 days and must be closed for clean up. Points split for possible solutions.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.