简体   繁体   中英

How do I remove values from select using knockout options binding?

I am using knockout to create a table that stores an array and I have a list of options that are created and put into an observable array. I want to be able to add the year to a table but have the value used removed from the select list. Currently I have the value added to the table with no problems but I can't seem to remove the values from the select list. Here is a fiddle I created.

var yearList = function(){  
    var years = [];
    var id = 0; 
    for(var y=1950; y < 2056; y++) {
        id++;
        years.push({
            id:id
            ,year:y
        });
     }
    return years;
 }

var ViewModel = function() {
    var self = this;
    self.years = ko.observableArray(yearList());
    self.selectedYear = {};
    self.yearTable = ko.observableArray([
    {
        id:1
        ,year:2013
    },{
        id:2
        ,year:2014
    }
    ]);

    self.addYear = function() {
        var addEntry = self.selectedYear;
        self.yearTable.push(addEntry);
        $( "#dialog" ).dialog( "close" );
    }
};

ko.applyBindings(new ViewModel()); 

 $(function() {
    $( "#dialog" ).dialog({
      autoOpen: false,
      show: {
        effect: "blind",
        duration: 1000
      },
      hide: {
        effect: "explode",
        duration: 1000
      }
    });

    $( document ).on('click','#newEntry',function() {
      $( "#dialog" ).dialog( "open" );
    });
});

Can some one assist please?

Use remove method http://knockoutjs.com/documentation/observableArrays.html http://jsfiddle.net/tarabyte/JTJ8n/12/

self.addYear = function() {
        var addEntry = self.selectedYear;
        self.yearTable.push(addEntry);
        self.years.remove(addEntry); //tada!
        $( "#dialog" ).dialog( "close" );
    }

You just need to call the .remove method on your self.years array.

See fiddle here: http://jsfiddle.net/JTJ8n/13/

Snippet:

self.addYear = function() {
    var addEntry = self.selectedYear;
    self.yearTable.push(addEntry);
    self.years.remove(addEntry);
    $( "#dialog" ).dialog( "close" );
}

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