Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 603
Eyup Can ARSLAN Avatar asked Oct 18 '25 09:10

Eyup Can ARSLAN


1 Answers

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>
like image 167
Rory McCrossan Avatar answered Oct 21 '25 00:10

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!