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
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:
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):
If you require more specificity, refine the conditional, for example (inside the document event listener function):
I generally use document event listeners by default, there is no extra computational cost and I find the single event listener easier to maintain.