Logan Jones
Logan Jones

Reputation: 77

How to get the Value of TD on click in MVC

I know this question gets asked alot but i have tried all of the clickevents for but cant seem to get this to work i am trying to get a value or string from a td here is the table i build

   <table id="tblMain">
  <thead>
    <tr>
        <th>Parcel ID</th>
        <th>Quick Ref ID</th>
        <th>Address</th>
        <th>Tax Unit</th>
        <th>Style</th>
        <th>Arch Style</th>
        <th>Validity Code</th>
        <th>Sale Price</th>
        <th>Sale Date</th>
        <th>Year Built</th>
        <th>Total Living Area</th>
        <th>Lot Area</th>
        <th>Bedrooms</th>
    </tr>
</thead>

<tbody>

    @foreach (var item in Model)
    {
        <tr class="side-link">


                <td class="parcelIDCell"><a id="Parcelid"    /> @item.ParcelId </td>
                <td>@item.QuickRefId</td>
                <td>@item.Address</td>
                <td>@item.TaxunitA</td>
                <td>@item.StyleA</td>
                <td>@item.ArchStyleA</td>
                <td>@item.ValCode</td>
                <td>@item.SalePriceA</td>
                <td>@item.SaleDateA</td>
                <td>@item.YearBuilt</td>
                <td>@item.LivingArea</td>
                <td>@item.LotArea</td>
                <td>@item.BedroomA</td>
                 @*<td>@item.ParcelID</td>
                <td>@item.PropertyID</td>*@

        </tr>
    }

</tbody>

i just want to retrieve the parcel Id from the first row depending on which one i click on some java script i have tried

 <script>
var tbl = document.getElementById("tblMain");
if (tbl != null) {
    for (var i = 0; i < tbl.rows.length; i++) {
        for (var j = 0; j < tbl.rows[i].cells.length; j++)
            tbl.rows[i].cells[j].onclick = function () { getval(this); };
    }
}

function getval(cel) {
    alert(cel.innerHTML);
}

there is more but i deleted them Any advice would be greatly appreciated

Upvotes: 1

Views: 2656

Answers (2)

jmore009
jmore009

Reputation: 12923

you want either an id or the string? You can do this:

$("td").click(function() {
  if($(this).hasClass("parcelIDCell")){
  var ID = $(this).find("a").attr("id");
  alert("Id is: " + ID);
 }else{
   var String = $(this).text();
   alert("Text is: " + String);
 }
});

It checks to see if the td being clicked has the class parcelIDCell, if it does it will find the a tag inside it and pull the id. If the class does not exist, it will just grab the text instead. Fiddle below:

FIDDLE

Upvotes: 2

vcanales
vcanales

Reputation: 1828

With jQuery:

$("#tblMain td").click(function() {
  if ($(this).hasClass('parcelIDCell') {
     alert($(this).find('a').attr('id));
  } else {
     alert($(this).text());
  }
});

Update: getting the parcel id or the text, depending on the class of the td.

Upvotes: 1

Related Questions