skip to Main Content

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.

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. You can set a single click event listener on the document and use a conditional inside its function to apply the same statement block to any groups of elements.

    For example, you could filter for targets that have id begining with the string "id" like this (core js):

    document.addEventListener('click', event => {
    
      if (event.target.id.indexOf('id') == 0) {
         // commands to apply to those elements;
      } // end if #id* click;
    
    // any number of other groups or individual elements can be added, each with a conditional to filter the required ones.
    
    }); // end event listener
    
    

    If you require more specificity, refine the conditional, for example (inside the document event listener function):

    const id=event.target.id;
    if (id == "id1" || id == "id3" || id == "somethingElse") {
    // relevant statements;
    };
    

    I generally use document event listeners by default, there is no extra computational cost and I find the single event listener easier to maintain.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search