How to masked an input text box which is data-boun

2019-08-05 20:36发布

问题:

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