Search code examples
javascripthtmlasp.net-corerazor

Javascript - need to get a value from an HTML table ROW/CELL and then check true or false in script


I have a simple table. When a user clicks on a row, a jscript gets triggered. How can I get a value from row/cell to use in jscript to check true or false please? There is also a seperate click-row script but ignore that for now.

<tbody>
@if (Model != null)
{
  foreach (CELIntranet.Models.tblReportsList item in Model)
  {
  <tr class="clickable-row" id="myid" data-mydata1=UserPermission href="@Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
                                   ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
      <td>@Html.Raw(item.ReportNumber)</td>
      <td>@Html.Raw(item.ReportName)</td>
      <td>@Html.Raw(item.ReportGroup)</td>
      <td>@Html.Raw(item.ReportStatus)</td>

    @if (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))
    {
      <td style="color:dodgerblue">Granted</td>
    }
    else
    {
      <td style="color:orangered">Restricted</td>
    }
  </tr>
  }
}
</tbody>

<script type="text/javascript">

    $(function () {

        var ClickedTableRowCellValue = ("Need some code to get UserPermission value from the clicked row");

        $('table > tbody > tr').click(function () {

            if (ClickedTableRowCellValue == True) {
                alert("Granted");
                Popup();
            }
            alert("Restricted");
        });
    });

</script>




// Click row ignore this code for now!

@section Scripts {

<script type="text/javascript">

    var clicker = new TableCliker();

    $(document).ready(function () {
    clicker.Initialise();
    //alert("Test");
    //Popup();
    });

</script>

Solution

  • Try to change your html like this:

    <tr class="clickable-row" id="myid" onclick="test(this)" UserPermission = "@(User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator"))" data-mydata1=UserPermission href="@Url.Action("ShowReport", new { ReportViewName = item.ReportViewName,
                                       ReportController = item.ReportController, UserPermission = (User.IsInRole(item.ReportUserRoles) || User.IsInRole("Administrator")) })">
    

    So that you can add UserPermission attribute to <tr></tr>.Here is the js:

    function test(t){
         var ClickedTableRowCellValue = $(t).attr("UserPermission").
         if (ClickedTableRowCellValue == True) {
                    alert("Granted");
                    Popup();
                }
                alert("Restricted");
    }