make an input only-numeric type on knockout

后端 未结 10 908
情书的邮戳
情书的邮戳 2020-11-30 06:15

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:[\         


        
相关标签:
10条回答
  • 2020-11-30 06:21

    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 }"
    
    0 讨论(0)
  • 2020-11-30 06:29

    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

    0 讨论(0)
  • 2020-11-30 06:31

    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();
        });
    }};
    
    0 讨论(0)
  • 2020-11-30 06:33

    Is better to create custom binding http://knockoutjs.com/documentation/custom-bindings.html which accept only allowed characters [0-9,.] as numeric representation.

    put this line into your view

    <input id="text" type="text" data-bind="numeric, value: number">
    

    put this line into your model (remember to bind number as observable property)

    ko.bindingHandlers.numeric = {
        init: function (element, valueAccessor) {
            $(element).on("keydown", function (event) {
                // Allow: backspace, delete, tab, escape, and enter
                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
                    // Allow: Ctrl+A
                    (event.keyCode == 65 && event.ctrlKey === true) ||
                    // Allow: . ,
                    (event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
                    // Allow: home, end, left, right
                    (event.keyCode >= 35 && event.keyCode <= 39)) {
                    // let it happen, don't do anything
                    return;
                }
                else {
                    // Ensure that it is a number and stop the keypress
                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    }
                }
            });
        }
    };
    
    0 讨论(0)
  • 2020-11-30 06:34

    Create you data-bind pointing at your shiny new code:

    <input id="price" name="price" type="text" data-bind="numeric">
    

    Shiny new knockout code:

    price = ko.observable();
    price.subscribe(function(newValue) {
        price = newValue.replace(/[\D\.]/g, '');
    });
    

    This means that every time you update the price, it will apply the logic in the function (in this case stripping out anything that isn't a number or a period), and apply it directly to the price. You can also add other validation or cool features here, like adding a currency sybmol at the start, keeping it to 2 decimal places, etc...

    0 讨论(0)
  • 2020-11-30 06: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();                 
            });           
        });
    
    0 讨论(0)
提交回复
热议问题