Eyup Can ARSLAN
Eyup Can ARSLAN

Reputation: 742

How To Use OnClick Function In jQuery From MVC View Foreach

I have a question on jQuery onClick function with foreach using.(I am new on jQuery.)

<table>
  <th>CityName</th>
  <th>CityId</th>
  @foreach (var item in Model.Adress)
  {   
    <tr>
      <td>
        <div onClick(cityDetail(@item.CityId, @item.cityName))>@CityId</div>
      </td>
      <td>
        <div>@CityName</div>
      </td>
    </tr>
  }
</table>

<script> 
  function cityDetail(cityId, cityName) {
    //do something
  }
</script>

My question is that, how can I do this only with jQuery? onClick(cityDetail(@item.CityId,@item.cityName). I want to use foreach and pass clicked multiple parameters to jQuery.

Thanks a lot for your answer.

Upvotes: 4

Views: 4559

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

It's generally a good idea to avoid all on* event attributes as it ties the HTML and JS code together too tightly. Instead, attach event handlers using unobtrusive Javascript. You can pass the CityId and CityName values to the event handler through data attributes on the elements created in the loop.

Also note that your HTML has some issues, such as a missing <tr> around the th, and the column headings in the wrong order to the data underneath.

With all that said, try this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(function() {
    $('.city').click(function() {
      var $city = $(this);
      cityDetail($city.data('city-id'), $city.data('city-name'));
    });
  });
</script>
<table>
  <tr>
    <th>City Id</th>
    <th>City Name</th>
  </tr>
  @foreach (var item in Model.Adress) {
    <tr>
      <td>
        <div class="city" data-city-id="@item.CityId" data-city-name="@item.cityName">@item.CityId</div>
      </td>
      <td>
        <div>@item.cityName</div>
      </td>
    </tr>
  }
</table>

Upvotes: 7

Related Questions