Search code examples
jqueryasp.net-mvctwitter-bootstraptooltip

MVC - How to display bootstrap tooltip for the cells with data ONLY


I have the following html:

<tr class=@(item.Index % 2 == 0? "even" : "odd")>
    <td>@Html.DisplayFor(modelItem => item.Data.ProductId)</td>
    <td>@Html.DisplayFor(modelItem => item.Data.ProductName)</td>
    <td id="cost" title="@item.Data.ToolTip" data-toggle="tooltip" data-container="body" data-placement="right">@Html.DisplayFor(modelItem => item.Data.ProductCost,"Currency")</td>
    <td>@Html.DisplayFor(modelItem => item.Data.ToolTip)</td>
</tr>

and a jquery for toggling tooltip:

$(function () {
    if ($('#cost').text() != '') {
        $('[data-toggle="tooltip"]').tooltip();
    }
});

I want to display tooltips only in case if cell has a data. The way I have does not seem to be working. What am I missing?


Solution

  • Add a span into the td and have the tooltip on the span. Then if there is no content in the span - hide it. Also note that you need to have unique id's for the table so that #cost might needs to be altered if you have more than one row with this struture.

    <tr class=@(item.Index % 2 == 0? "even" : "odd")>
        <td>@Html.DisplayFor(modelItem => item.Data.ProductId)</td>
        <td>@Html.DisplayFor(modelItem => item.Data.ProductName)</td>
        <td id="cost"><span title="@item.Data.ToolTip" data-toggle="tooltip" data-container="body" data-placement="right">@Html.DisplayFor(modelItem => item.Data.ProductCost,"Currency")</span></td>
        <td>@Html.DisplayFor(modelItem => item.Data.ToolTip)</td>
    </tr>
    

    and a jquery for toggling span:

    $(function () {
      $('[data-toggle="tooltip"]').tooltip();
      $('#cost span').each(function(){
        if ($(this).text() === '') {
          $(this).hide();
        }
      });
    });