Vaibhav Sidapara Vaibhav Sidapara - 1 month ago 10
Javascript Question

JQuery onchange for multiple elements but trigger only once

I have many select boxes in an HTML page and I have used the same class name 'paperGSM' for all select elements and a function which triggers on change of the select box elements value.

var getPaperTypeFromGSM = function()
{
$('div').off().on('change', '.paperGSM', function ()
{
console.log($(this).val());
var url = 'api/getPaperTypeFromGSM';
var postData = {
paperGSM: $(this).val()
};
var $current = $(this);
$.post(url, postData, function (result)
{
if (result.result == 1) {
var output = "";
output += '<option value="0">Select Paper Type</option>';
for (var i = 0; i <result.paperType.length; i++) {
output += '<option value="' + result.paperType[i].paper_type_id + '">' + result.paperType[i].paper_type_name + '</option>';
}
$current.siblings('.paperType').prop("disabled", false).html(output);
getPaperSizeFromPaperType();
} else {
Result.error(result);
}
}, 'json');
});
return false;
};


Every time the change event occurs it triggers multiple times (maybe it triggers for all the elements with the same class name). The image below explains the situation.

P.S: My logic and even the post function are working fine

As I do not want to hardcode the events for all elements (like give all elements different class name and hardcode the functions for all), I only want one function working for all the same class elements but trigger it only once.

If I ignore the multiple triggers everything is working fine it's just that, that thing is bothering me a lot.

enter image description here

Answer

The reason is due to eventBubbling. To stop try this

$('div').on('change', '.paperGSM', function (event){ 
event.stopPropagation(); 
// ...and rest of your codes..
}

NB: Remove the .off as it will remove listener once this event is triggered.

Comments