How to masked an input text box which is data-bound to Knockout computed variable

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-14 02:48:48

问题


I am using jquery MASKED INPUT PLUGIN for masking my input boxes which are data-binded to knockout variables. I have problem in masking if the knockout variable is Computed Variable.

Here is the Fiddler Link https://jsfiddle.net/himanshudhiman/2h1f18qo/5/

I am able to mask input boxes of observable array. But I don't get masking option for the input box of Computed Variable(i.e here in my code is "self.SelectById()").

ViewModel

function KeyValuePairOfIdAndName(Name, ID) {
            var self = this;
            self.Name = Name;
            self.ID = ID;
        }

var ViewModel = function () {
    var self = this;
    self.listOfkeyValue = ko.observableArray();
    self.SelectById = ko.computed(function () {
        return ko.utils.arrayFilter(self.listOfkeyValue(), function (Fruit) {
            return Fruit.ID == 1001;
        });
    });
    var count = 1;
    self.CreateNewFruit = function () {

        self.listOfkeyValue.push(new KeyValuePairOfIdAndName("Apple" + count, 999 + count));
        $(".inputboxofEachFruit").mask("9999");
        count = count + 1;

    }

}

$(document).ready(function () {
    var viewModel = new ViewModel();
    ko.applyBindings(viewModel);
    $(".inputboxofEachFruit").mask("9999");
    $(".inputboxofSelectedFruit").mask("9999");
});

HTML

<button data-bind="event: { mousedown: CreateNewFruit }" >Createe Fruit</button>    
<br/>  
Fruits From Observable Array
<div data-bind="foreach: listOfkeyValue" >                            
    <input class = "inputboxofEachFruit" data-bind="value: ID"/>   
</div>
<br/>  
<span style = "color:Red;">Fruits From computed variable</span>
<div data-bind="foreach: SelectById" >                            
    <input class = "inputboxofSelectedFruit" data-bind="value: ID"/>   
</div>

I have an idea that, i need to bind dynamically created variables to mask's property and i have done that in "self.CreateNewFruit()" after pushing new element in "self.listOfkeyValue()". But what to do with Computed Variables. How to mask them.


回答1:


one way would be using trigger to add .mask when ever new element is created

Code:

$("#cool").on("click", function () {
   $(".one").mask("9999"); //dynamic elements with same class name get's mask
});
 $("#cool").trigger("click");

working sample with your code here

other simple way would be under your ko click event add .mask on class name make sure you maintain same class across mask-able elements like here



来源:https://stackoverflow.com/questions/32632265/how-to-masked-an-input-text-box-which-is-data-bound-to-knockout-computed-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!