简体   繁体   中英

jquery select2 .on(“change”, function(e) reset option

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 .

try 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

您可以使用off从元素中分离事件处理程序,如下所示:

$("#selected_countries").off('change');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM