i am using select2.
Usage : if a value is "COUNTRY"
, i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :
var reportLevel = getReportLevel();
if (reportLevel != "COUNTRY") {
$("#selected_countries").on("change", function(e) {
prepareGlidModel(e);
});
} else {
$("#selected_countries").on("change", function(e) {
});
}
Issue : Not being able to remove the onchange event, even if the else block is called.
Events are called based upon the reportLevel
value selected in a dropdown
.
i am using select2.
Usage : if a value is "COUNTRY"
, i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :
var reportLevel = getReportLevel();
if (reportLevel != "COUNTRY") {
$("#selected_countries").on("change", function(e) {
prepareGlidModel(e);
});
} else {
$("#selected_countries").on("change", function(e) {
});
}
Issue : Not being able to remove the onchange event, even if the else block is called.
Events are called based upon the reportLevel
value selected in a dropdown
.
- For remove an event you have to use off instead of on – Daniele Commented Aug 1, 2013 at 14:49
- hey @Daniele, can you please gimme an example – Pravat Panda Commented Aug 1, 2013 at 14:52
- I think something like $("#selected_countries").off("change"); Check jquery off – Daniele Commented Aug 1, 2013 at 14:53
3 Answers
Reset to default 10try following:
var reportLevel = getReportLevel(),
// by default unbind/off change event
$select = $("#selected_countries").off("change");
// and if country then bind it
if (reportLevel == "COUNTRY") {
$select.on("change", function(e) {
alert("you selected :" + $(this).val());
});
}
Working example here: http://jsfiddle.net/JB89B/1/
i think on else case you want to reset the value to default for this you have to use
$("#selected_countries").val('default value')
and if u just want to prevent the default action of onchange event than on else you can write
e.preventDefault()
this will help
You can use off to deatach event handlers from your elements as shown below:
$("#selected_countries").off('change');