Attempting to read text of element shows text of first element only

Viewed 55

I am fetching a list from a controller and displaying it in the view in tile format using ASP.Net MVC.

When I click on a particular tile it should display an alert message of the application name for that particular tile. However whichever tile I click I am getting the first application name for all the tiles. Please help.

<div class="container">
  <section class="cms-boxes">
    <div class="container-fluid">
      <div class="row">
        @foreach (var item in Model) 
        {
          <div class="col-md-4 cms-boxes-outer">
            <div class="cms-boxes-items cms-features">
              <div class="boxes-align">
                <div class="small-box">
                  <h2 class="appnamedisplay">@Html.DisplayFor(modelItem => item.ApplicationName)</h2>
                  <p>@Html.DisplayFor(modelItem => item.number)</p>
                </div>
              </div>
            </div>
          </div>
        }
      </div>
    </div>
  </section>
</div>
$(document).ready(function() {
  $(".small-box").click(function() {
    var name = $(".appnamedisplay").html();
    alert(name);
  });
});
1 Answers

The issue is because you're selecting all the .appnamedisplay elements. Calling html() on that collection will only show you the value of the first element in that set.

To fix the issue, use DOM traversal to find the specific .appnamedisplay element which is related to the clicked .small-box. To do that use the this keyword to refer to the element which raised the event, and jQuery's find() method:

$(".small-box").click(function () {
  var name = $(this).find(".appnamedisplay").html();            
  console.log(name);
});

Also note the preferred use of console.log() to debug, as it doesn't block the UI from updating and also doesn't coerce data types as alert() does.

Related