make an input only-numeric type on knockout

2019-01-07 15:00发布

i read many tutorials but i dont know how to do this, this is the input

input(type="text",name="price",id="price"data-bind="text: price,valueUpdate:['afterkeydown','propertychange','input']")

and this is my viewModel

price: ko.computed(function()
{
    return parseFloat(this.replace(' ','').replace(/[^0-9\.]+/g,"")) || '';
},this)

but this cause error: this has no method replace??? how can i pass the price value to the computed function??

10条回答
三岁会撩人
2楼-- · 2019-01-07 15:28

I had a similar problem.

I also needed to ensure inter values only, and for IE9 and up (so type=numberical was not enough), and since we have a lot of international customers, i could not rely on keycodes either, so the following is what i ended up with:

//In my js class method (self is this as usual)
self.ensureNumberical = function (data, e) {
    var keyValue = e.key;
    if (keyValue.match(/[0-9]/g)) {
        return true;
    }
    return false;
}

//In my MVC View
data-bind="event: { keypress: ensureNumberical }"
查看更多
干净又极端
3楼-- · 2019-01-07 15:29

I know this question is a year old but let me post this for the sake of feature visitor of the page.

Check this out:

ko.bindingHandlers.numericnumbers = {
init: function (element) {
    $(element).on('keypress', function (number) {
        number = (number) ? number : window.event;
        var charcode = (number.which) ? number.which : number.keyCode;
        if (charcode > 31 && (charcode < 48 || charcode > 75))
            number.preventDefault();
    });
}};
查看更多
戒情不戒烟
4楼-- · 2019-01-07 15:31

Best for today's scenerio https://github.com/Knockout-Contrib/Knockout-Validation

run the snippet below. entering a non digit or something more than 255 will cause the message to display.

function model() {
  var self = this;
  this.myObj = ko.observable().extend({ digit: true }).extend({ max: 255});
  }
  
  var mymodel = new model();

$(document).ready(function() {
  ko.validation.init();
  ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>

enter a digit less than or equal to  255 <input type="text" data-bind="textInput: myObj">

<p>
  Enter something other than a digit or over 255 will cause an error.
</p>

courtesy: Bryan Dellinger: https://stackoverflow.com/a/42940109/3868653

查看更多
一纸荒年 Trace。
5楼-- · 2019-01-07 15:33

An alternative approach: I have found that Knockout works well in combination with jQuery-validate. You just need to make sure that you validate the form before you attempt to use the numeric value.

Say you have a form DOM element, you can set up validation rules via

$(".yourform").validate({
    rules: {
        year: {
            digits: true,
            minlength: 4,
            maxlength: 4
        }
    },
    messages: {
        year: "Please enter four digits (e.g. 2009).",
    }
});

In your viewmodel you set the two-way binding up as usual, e.g. via self.year = ko.observable(""). Now make sure that you call $(".yourform").valid() before you are further processing self.year(). In my case, I am doing var year = parseInt(self.year(), 10). Right after form validation this is expected to always produce a meaningful result.

查看更多
Summer. ? 凉城
6楼-- · 2019-01-07 15:34

With the help of "keydown" event we can restrict other key's in text box which should hold numeric values.

$(document).ready(function(){                
        $("selector").on("keydown", function (e) {
            //numbers, delete, backspace, arrows
            var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
            if (!($.inArray(e.keyCode, validKeyCodes) >= 0))
                    e.preventDefault();                 
        });           
    });
查看更多
Viruses.
7楼-- · 2019-01-07 15:36
 <input type="text" id="alpha-validation" data-bind="value: YourDataName, valueUpdate: 'afterkeydown' , event: { 'input': AlphaCheck}" style="text-transform:uppercase">

create AlphaCheck Function and add that.

    $('#alpha-validation').keyup(function () {
        if (this.value.match(/[^0-9 ]/g)) {
            this.value = this.value.replace(/[^0-9 ]/g, '');
        }
    });

That will works!

查看更多
登录 后发表回答