最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery select2 .on("change", function(e) reset option - Stack Overflow

programmeradmin0浏览0评论

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.

Share Improve this question asked Aug 1, 2013 at 14:45 Pravat PandaPravat Panda 1,0902 gold badges14 silver badges27 bronze badges 3
  • 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
Add a comment  | 

3 Answers 3

Reset to default 10

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

You can use off to deatach event handlers from your elements as shown below:

$("#selected_countries").off('change');
发布评论

评论列表(0)

  1. 暂无评论