Home > Software design >  Jquery - how to add a click event for each button
Jquery - how to add a click event for each button

Time:10-10

Using the below jquery, I am able to find each button with the id, what I can't get to happen is when I lick the button to actually load the URL. How can I modify the jquery so when I click the button it will before the load?

<script>
$(document).ready(function() {
    var url = '@Url.Action("_Research", "Dashboard")';
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(
        function (currentBtn) {
            alert(currentBtn.id);
            currentBtn.click(function() {
                $('#researchDiv').load(url, {
                    ticker: currentBtn.id
                })
            });
        }
    );
});
</script>

CodePudding user response:

Since you're using jQuery, you don't need a loop. The jQuery event binding method automatically loops over all the elements. Then you can use this to refer to the button that was clicked.

$(document).ready(function() {
  var url = '@Url.Action("_Research", "Dashboard")';
  const buttons = document.querySelectorAll('.btn');
  $(".btn").click(function() {
    $('#researchDiv').load(url, {
      ticker: this.id
    })
  });
});

  • Related