Skip to content
Advertisement

create onclick event for multiple ids

I have written a js function:

$(document).on('click', '#id1', function () {
$.ajax({
  type: "POST",
  url: "/url",
  data: { uInput: 'id1' },
  success: function (response) {
    some code....
  },
  error: function (error) {
    console.log(error);
  }
});
});

Problem is, since I have more clickable objects with various IDs, i wanted to create a single script/function that would accept onclick event from not only #id1, but also #id2, #id3 etc…

I tried following advice found here: https://stackoverflow.com/a/18508894/11271927 and here https://stackoverflow.com/a/18508907/11271927 but whenever I would edit the code to acomodate my code structure, it wouldnt work.

var options = {
    id1: 'id1',
    id2: 'id2',
    id3: 'id3',
    id4: 'id4'
  };
  $('.options').click(function () {
    $.ajax({
      type: "POST",
      url: "/url",
      data: options[this.id],
      success: function (response) {
        some code....
      },
      error: function (error) {
        console.log(error);
      }
    });
  });

Essentially, this code doesnt do anythign on click.

If you know what I have missed or done wrong, please help.

Advertisement

Answer

If you want to have one function that will have a click listener on several elements (for example by class) you can try it like this:

<button class="button" id="id1">A</button>
<button class="button" id="id2">B</button>
<button class="button" id="id3">C</button>

<script>
    $(document).on('click', '.button', function () {
        $.ajax({
            type: "POST",
            url: "/url",
            data: {
                uInput: this.getAttribute('id'),
            },
            success: function (response) {
                console.log(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
    });
</script>
Advertisement