I currently use javascript to create a html table.
When the user clicks on a button. It appends a tr
to the table.
Inside the tr
I also append a select2 <select>
element.
The method I did so far was to make the id of the select
element to be accompanied by a number. It was something like item-project-no-0
and item-project-no-1
.
But now I need to register the event listener for all the select
elements in that table. Initially, I thought that it would be something like this:
$('#item-project-no-' + x).on('select2:select', function (e) {
});
There is another method another person that had suggested was to use something like this:
$(document).on("select2:select", ".myClass", function() {
console.log("event fired");
}
I am not sure is it because I don’t have a very good understanding of jquery/javascript. Because I assumed that only when a selection is made then the string “event fired” will be logged on the console? Its seems that even when the select
element is being created and appended to the tr
, the string “event fired” was also logged on the console.
I also need assistance related to this problem. I currently initialise the select
element I was talking about above like this:
$("#item-project-no-" + numberCounter).select2({
ajax: {
url: currentUrl + "api/INV_API/projSelect2",
data: function (params) {
return {
q: params.term, // search term
};
},
dataType: 'json',
type: "GET",
processResults: function (data) {
return {
results: $.map(data, function (obj) {
if (obj.SUBNO == "") {
return { id: obj.JOBNO, text: obj.JOBNO + "-" + obj.SHORTNM };
} else {
return { id: obj.JOBNO, text: obj.JOBNO + "-" + obj.SHORTNM + ":" + obj.SUBNO };
}
})
};
}
}
});
When using the method below, how do I access the selected option’s value? Does it involve the use of $(this)
?
$(document).on("select2:select", ".myClass", function() {
}